'use strict';

var WebSocket = require('ws');

function asyncGeneratorStep(n, t, e, r, o, a, c) {
  try {
    var i = n[a](c),
      u = i.value;
  } catch (n) {
    return void e(n);
  }
  i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
  return function () {
    var t = this,
      e = arguments;
    return new Promise(function (r, o) {
      var a = n.apply(t, e);
      function _next(n) {
        asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
      }
      function _throw(n) {
        asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
      }
      _next(void 0);
    });
  };
}

var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

var regeneratorRuntime$1 = {exports: {}};

var _typeof$1 = {exports: {}};

(function (module) {
	function _typeof(o) {
	  "@babel/helpers - typeof";

	  return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
	    return typeof o;
	  } : function (o) {
	    return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
	  }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o);
	}
	module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; 
} (_typeof$1));

var _typeofExports = _typeof$1.exports;

(function (module) {
	var _typeof = _typeofExports["default"];
	function _regeneratorRuntime() {
	  module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
	    return e;
	  }, module.exports.__esModule = true, module.exports["default"] = module.exports;
	  var t,
	    e = {},
	    r = Object.prototype,
	    n = r.hasOwnProperty,
	    o = Object.defineProperty || function (t, e, r) {
	      t[e] = r.value;
	    },
	    i = "function" == typeof Symbol ? Symbol : {},
	    a = i.iterator || "@@iterator",
	    c = i.asyncIterator || "@@asyncIterator",
	    u = i.toStringTag || "@@toStringTag";
	  function define(t, e, r) {
	    return Object.defineProperty(t, e, {
	      value: r,
	      enumerable: !0,
	      configurable: !0,
	      writable: !0
	    }), t[e];
	  }
	  try {
	    define({}, "");
	  } catch (t) {
	    define = function define(t, e, r) {
	      return t[e] = r;
	    };
	  }
	  function wrap(t, e, r, n) {
	    var i = e && e.prototype instanceof Generator ? e : Generator,
	      a = Object.create(i.prototype),
	      c = new Context(n || []);
	    return o(a, "_invoke", {
	      value: makeInvokeMethod(t, r, c)
	    }), a;
	  }
	  function tryCatch(t, e, r) {
	    try {
	      return {
	        type: "normal",
	        arg: t.call(e, r)
	      };
	    } catch (t) {
	      return {
	        type: "throw",
	        arg: t
	      };
	    }
	  }
	  e.wrap = wrap;
	  var h = "suspendedStart",
	    l = "suspendedYield",
	    f = "executing",
	    s = "completed",
	    y = {};
	  function Generator() {}
	  function GeneratorFunction() {}
	  function GeneratorFunctionPrototype() {}
	  var p = {};
	  define(p, a, function () {
	    return this;
	  });
	  var d = Object.getPrototypeOf,
	    v = d && d(d(values([])));
	  v && v !== r && n.call(v, a) && (p = v);
	  var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
	  function defineIteratorMethods(t) {
	    ["next", "throw", "return"].forEach(function (e) {
	      define(t, e, function (t) {
	        return this._invoke(e, t);
	      });
	    });
	  }
	  function AsyncIterator(t, e) {
	    function invoke(r, o, i, a) {
	      var c = tryCatch(t[r], t, o);
	      if ("throw" !== c.type) {
	        var u = c.arg,
	          h = u.value;
	        return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
	          invoke("next", t, i, a);
	        }, function (t) {
	          invoke("throw", t, i, a);
	        }) : e.resolve(h).then(function (t) {
	          u.value = t, i(u);
	        }, function (t) {
	          return invoke("throw", t, i, a);
	        });
	      }
	      a(c.arg);
	    }
	    var r;
	    o(this, "_invoke", {
	      value: function value(t, n) {
	        function callInvokeWithMethodAndArg() {
	          return new e(function (e, r) {
	            invoke(t, n, e, r);
	          });
	        }
	        return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
	      }
	    });
	  }
	  function makeInvokeMethod(e, r, n) {
	    var o = h;
	    return function (i, a) {
	      if (o === f) throw Error("Generator is already running");
	      if (o === s) {
	        if ("throw" === i) throw a;
	        return {
	          value: t,
	          done: !0
	        };
	      }
	      for (n.method = i, n.arg = a;;) {
	        var c = n.delegate;
	        if (c) {
	          var u = maybeInvokeDelegate(c, n);
	          if (u) {
	            if (u === y) continue;
	            return u;
	          }
	        }
	        if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
	          if (o === h) throw o = s, n.arg;
	          n.dispatchException(n.arg);
	        } else "return" === n.method && n.abrupt("return", n.arg);
	        o = f;
	        var p = tryCatch(e, r, n);
	        if ("normal" === p.type) {
	          if (o = n.done ? s : l, p.arg === y) continue;
	          return {
	            value: p.arg,
	            done: n.done
	          };
	        }
	        "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
	      }
	    };
	  }
	  function maybeInvokeDelegate(e, r) {
	    var n = r.method,
	      o = e.iterator[n];
	    if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
	    var i = tryCatch(o, e.iterator, r.arg);
	    if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
	    var a = i.arg;
	    return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
	  }
	  function pushTryEntry(t) {
	    var e = {
	      tryLoc: t[0]
	    };
	    1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
	  }
	  function resetTryEntry(t) {
	    var e = t.completion || {};
	    e.type = "normal", delete e.arg, t.completion = e;
	  }
	  function Context(t) {
	    this.tryEntries = [{
	      tryLoc: "root"
	    }], t.forEach(pushTryEntry, this), this.reset(!0);
	  }
	  function values(e) {
	    if (e || "" === e) {
	      var r = e[a];
	      if (r) return r.call(e);
	      if ("function" == typeof e.next) return e;
	      if (!isNaN(e.length)) {
	        var o = -1,
	          i = function next() {
	            for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
	            return next.value = t, next.done = !0, next;
	          };
	        return i.next = i;
	      }
	    }
	    throw new TypeError(_typeof(e) + " is not iterable");
	  }
	  return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
	    value: GeneratorFunctionPrototype,
	    configurable: !0
	  }), o(GeneratorFunctionPrototype, "constructor", {
	    value: GeneratorFunction,
	    configurable: !0
	  }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
	    var e = "function" == typeof t && t.constructor;
	    return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
	  }, e.mark = function (t) {
	    return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
	  }, e.awrap = function (t) {
	    return {
	      __await: t
	    };
	  }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
	    return this;
	  }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
	    void 0 === i && (i = Promise);
	    var a = new AsyncIterator(wrap(t, r, n, o), i);
	    return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
	      return t.done ? t.value : a.next();
	    });
	  }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
	    return this;
	  }), define(g, "toString", function () {
	    return "[object Generator]";
	  }), e.keys = function (t) {
	    var e = Object(t),
	      r = [];
	    for (var n in e) r.push(n);
	    return r.reverse(), function next() {
	      for (; r.length;) {
	        var t = r.pop();
	        if (t in e) return next.value = t, next.done = !1, next;
	      }
	      return next.done = !0, next;
	    };
	  }, e.values = values, Context.prototype = {
	    constructor: Context,
	    reset: function reset(e) {
	      if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
	    },
	    stop: function stop() {
	      this.done = !0;
	      var t = this.tryEntries[0].completion;
	      if ("throw" === t.type) throw t.arg;
	      return this.rval;
	    },
	    dispatchException: function dispatchException(e) {
	      if (this.done) throw e;
	      var r = this;
	      function handle(n, o) {
	        return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
	      }
	      for (var o = this.tryEntries.length - 1; o >= 0; --o) {
	        var i = this.tryEntries[o],
	          a = i.completion;
	        if ("root" === i.tryLoc) return handle("end");
	        if (i.tryLoc <= this.prev) {
	          var c = n.call(i, "catchLoc"),
	            u = n.call(i, "finallyLoc");
	          if (c && u) {
	            if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
	            if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
	          } else if (c) {
	            if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
	          } else {
	            if (!u) throw Error("try statement without catch or finally");
	            if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
	          }
	        }
	      }
	    },
	    abrupt: function abrupt(t, e) {
	      for (var r = this.tryEntries.length - 1; r >= 0; --r) {
	        var o = this.tryEntries[r];
	        if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
	          var i = o;
	          break;
	        }
	      }
	      i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
	      var a = i ? i.completion : {};
	      return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
	    },
	    complete: function complete(t, e) {
	      if ("throw" === t.type) throw t.arg;
	      return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
	    },
	    finish: function finish(t) {
	      for (var e = this.tryEntries.length - 1; e >= 0; --e) {
	        var r = this.tryEntries[e];
	        if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
	      }
	    },
	    "catch": function _catch(t) {
	      for (var e = this.tryEntries.length - 1; e >= 0; --e) {
	        var r = this.tryEntries[e];
	        if (r.tryLoc === t) {
	          var n = r.completion;
	          if ("throw" === n.type) {
	            var o = n.arg;
	            resetTryEntry(r);
	          }
	          return o;
	        }
	      }
	      throw Error("illegal catch attempt");
	    },
	    delegateYield: function delegateYield(e, r, n) {
	      return this.delegate = {
	        iterator: values(e),
	        resultName: r,
	        nextLoc: n
	      }, "next" === this.method && (this.arg = t), y;
	    }
	  }, e;
	}
	module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports; 
} (regeneratorRuntime$1));

var regeneratorRuntimeExports = regeneratorRuntime$1.exports;

// TODO(Babel 8): Remove this file.

var runtime = regeneratorRuntimeExports();
var regenerator = runtime;

// Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
try {
  regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
  if (typeof globalThis === "object") {
    globalThis.regeneratorRuntime = runtime;
  } else {
    Function("r", "regeneratorRuntime = r")(runtime);
  }
}

var _regeneratorRuntime = /*@__PURE__*/getDefaultExportFromCjs(regenerator);

function _classCallCheck$1(a, n) {
  if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
}

function _typeof(o) {
  "@babel/helpers - typeof";

  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
    return typeof o;
  } : function (o) {
    return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  }, _typeof(o);
}

function toPrimitive(t, r) {
  if ("object" != _typeof(t) || !t) return t;
  var e = t[Symbol.toPrimitive];
  if (void 0 !== e) {
    var i = e.call(t, r || "default");
    if ("object" != _typeof(i)) return i;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return ("string" === r ? String : Number)(t);
}

function toPropertyKey(t) {
  var i = toPrimitive(t, "string");
  return "symbol" == _typeof(i) ? i : i + "";
}

function _defineProperties$1(e, r) {
  for (var t = 0; t < r.length; t++) {
    var o = r[t];
    o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, toPropertyKey(o.key), o);
  }
}
function _createClass$1(e, r, t) {
  return r && _defineProperties$1(e.prototype, r), t && _defineProperties$1(e, t), Object.defineProperty(e, "prototype", {
    writable: !1
  }), e;
}

function _defineProperty$1(e, r, t) {
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
    value: t,
    enumerable: !0,
    configurable: !0,
    writable: !0
  }) : e[r] = t, e;
}

var versionMapping = Object.create(null);
function register(version, api) {
  versionMapping[version] = api;
}

function bind(fn, thisArg) {
  return function wrap() {
    return fn.apply(thisArg, arguments);
  };
}

// utils is a library of generic helper functions non-specific to axios

const {toString} = Object.prototype;
const {getPrototypeOf} = Object;

const kindOf = (cache => thing => {
    const str = toString.call(thing);
    return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(Object.create(null));

const kindOfTest = (type) => {
  type = type.toLowerCase();
  return (thing) => kindOf(thing) === type
};

const typeOfTest = type => thing => typeof thing === type;

/**
 * Determine if a value is an Array
 *
 * @param {Object} val The value to test
 *
 * @returns {boolean} True if value is an Array, otherwise false
 */
const {isArray} = Array;

/**
 * Determine if a value is undefined
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if the value is undefined, otherwise false
 */
const isUndefined = typeOfTest('undefined');

/**
 * Determine if a value is a Buffer
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Buffer, otherwise false
 */
function isBuffer(val) {
  return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
    && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}

/**
 * Determine if a value is an ArrayBuffer
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
 */
const isArrayBuffer = kindOfTest('ArrayBuffer');


/**
 * Determine if a value is a view on an ArrayBuffer
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
 */
function isArrayBufferView(val) {
  let result;
  if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
    result = ArrayBuffer.isView(val);
  } else {
    result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
  }
  return result;
}

/**
 * Determine if a value is a String
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a String, otherwise false
 */
const isString = typeOfTest('string');

/**
 * Determine if a value is a Function
 *
 * @param {*} val The value to test
 * @returns {boolean} True if value is a Function, otherwise false
 */
const isFunction = typeOfTest('function');

/**
 * Determine if a value is a Number
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Number, otherwise false
 */
const isNumber = typeOfTest('number');

/**
 * Determine if a value is an Object
 *
 * @param {*} thing The value to test
 *
 * @returns {boolean} True if value is an Object, otherwise false
 */
const isObject = (thing) => thing !== null && typeof thing === 'object';

/**
 * Determine if a value is a Boolean
 *
 * @param {*} thing The value to test
 * @returns {boolean} True if value is a Boolean, otherwise false
 */
const isBoolean = thing => thing === true || thing === false;

/**
 * Determine if a value is a plain Object
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a plain Object, otherwise false
 */
const isPlainObject = (val) => {
  if (kindOf(val) !== 'object') {
    return false;
  }

  const prototype = getPrototypeOf(val);
  return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val);
};

/**
 * Determine if a value is a Date
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Date, otherwise false
 */
const isDate = kindOfTest('Date');

/**
 * Determine if a value is a File
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a File, otherwise false
 */
const isFile = kindOfTest('File');

/**
 * Determine if a value is a Blob
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Blob, otherwise false
 */
const isBlob = kindOfTest('Blob');

/**
 * Determine if a value is a FileList
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a File, otherwise false
 */
const isFileList = kindOfTest('FileList');

/**
 * Determine if a value is a Stream
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a Stream, otherwise false
 */
const isStream = (val) => isObject(val) && isFunction(val.pipe);

/**
 * Determine if a value is a FormData
 *
 * @param {*} thing The value to test
 *
 * @returns {boolean} True if value is an FormData, otherwise false
 */
const isFormData = (thing) => {
  let kind;
  return thing && (
    (typeof FormData === 'function' && thing instanceof FormData) || (
      isFunction(thing.append) && (
        (kind = kindOf(thing)) === 'formdata' ||
        // detect form-data instance
        (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
      )
    )
  )
};

/**
 * Determine if a value is a URLSearchParams object
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
 */
const isURLSearchParams = kindOfTest('URLSearchParams');

const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);

/**
 * Trim excess whitespace off the beginning and end of a string
 *
 * @param {String} str The String to trim
 *
 * @returns {String} The String freed of excess whitespace
 */
const trim = (str) => str.trim ?
  str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');

/**
 * Iterate over an Array or an Object invoking a function for each item.
 *
 * If `obj` is an Array callback will be called passing
 * the value, index, and complete array for each item.
 *
 * If 'obj' is an Object callback will be called passing
 * the value, key, and complete object for each property.
 *
 * @param {Object|Array} obj The object to iterate
 * @param {Function} fn The callback to invoke for each item
 *
 * @param {Boolean} [allOwnKeys = false]
 * @returns {any}
 */
function forEach(obj, fn, {allOwnKeys = false} = {}) {
  // Don't bother if no value provided
  if (obj === null || typeof obj === 'undefined') {
    return;
  }

  let i;
  let l;

  // Force an array if not already something iterable
  if (typeof obj !== 'object') {
    /*eslint no-param-reassign:0*/
    obj = [obj];
  }

  if (isArray(obj)) {
    // Iterate over array values
    for (i = 0, l = obj.length; i < l; i++) {
      fn.call(null, obj[i], i, obj);
    }
  } else {
    // Iterate over object keys
    const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
    const len = keys.length;
    let key;

    for (i = 0; i < len; i++) {
      key = keys[i];
      fn.call(null, obj[key], key, obj);
    }
  }
}

function findKey(obj, key) {
  key = key.toLowerCase();
  const keys = Object.keys(obj);
  let i = keys.length;
  let _key;
  while (i-- > 0) {
    _key = keys[i];
    if (key === _key.toLowerCase()) {
      return _key;
    }
  }
  return null;
}

const _global = (() => {
  /*eslint no-undef:0*/
  if (typeof globalThis !== "undefined") return globalThis;
  return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global)
})();

const isContextDefined = (context) => !isUndefined(context) && context !== _global;

/**
 * Accepts varargs expecting each argument to be an object, then
 * immutably merges the properties of each object and returns result.
 *
 * When multiple objects contain the same key the later object in
 * the arguments list will take precedence.
 *
 * Example:
 *
 * ```js
 * var result = merge({foo: 123}, {foo: 456});
 * console.log(result.foo); // outputs 456
 * ```
 *
 * @param {Object} obj1 Object to merge
 *
 * @returns {Object} Result of all merge properties
 */
function merge(/* obj1, obj2, obj3, ... */) {
  const {caseless} = isContextDefined(this) && this || {};
  const result = {};
  const assignValue = (val, key) => {
    const targetKey = caseless && findKey(result, key) || key;
    if (isPlainObject(result[targetKey]) && isPlainObject(val)) {
      result[targetKey] = merge(result[targetKey], val);
    } else if (isPlainObject(val)) {
      result[targetKey] = merge({}, val);
    } else if (isArray(val)) {
      result[targetKey] = val.slice();
    } else {
      result[targetKey] = val;
    }
  };

  for (let i = 0, l = arguments.length; i < l; i++) {
    arguments[i] && forEach(arguments[i], assignValue);
  }
  return result;
}

/**
 * Extends object a by mutably adding to it the properties of object b.
 *
 * @param {Object} a The object to be extended
 * @param {Object} b The object to copy properties from
 * @param {Object} thisArg The object to bind function to
 *
 * @param {Boolean} [allOwnKeys]
 * @returns {Object} The resulting value of object a
 */
const extend = (a, b, thisArg, {allOwnKeys}= {}) => {
  forEach(b, (val, key) => {
    if (thisArg && isFunction(val)) {
      a[key] = bind(val, thisArg);
    } else {
      a[key] = val;
    }
  }, {allOwnKeys});
  return a;
};

/**
 * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
 *
 * @param {string} content with BOM
 *
 * @returns {string} content value without BOM
 */
const stripBOM = (content) => {
  if (content.charCodeAt(0) === 0xFEFF) {
    content = content.slice(1);
  }
  return content;
};

/**
 * Inherit the prototype methods from one constructor into another
 * @param {function} constructor
 * @param {function} superConstructor
 * @param {object} [props]
 * @param {object} [descriptors]
 *
 * @returns {void}
 */
const inherits = (constructor, superConstructor, props, descriptors) => {
  constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  constructor.prototype.constructor = constructor;
  Object.defineProperty(constructor, 'super', {
    value: superConstructor.prototype
  });
  props && Object.assign(constructor.prototype, props);
};

/**
 * Resolve object with deep prototype chain to a flat object
 * @param {Object} sourceObj source object
 * @param {Object} [destObj]
 * @param {Function|Boolean} [filter]
 * @param {Function} [propFilter]
 *
 * @returns {Object}
 */
const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
  let props;
  let i;
  let prop;
  const merged = {};

  destObj = destObj || {};
  // eslint-disable-next-line no-eq-null,eqeqeq
  if (sourceObj == null) return destObj;

  do {
    props = Object.getOwnPropertyNames(sourceObj);
    i = props.length;
    while (i-- > 0) {
      prop = props[i];
      if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
        destObj[prop] = sourceObj[prop];
        merged[prop] = true;
      }
    }
    sourceObj = filter !== false && getPrototypeOf(sourceObj);
  } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);

  return destObj;
};

/**
 * Determines whether a string ends with the characters of a specified string
 *
 * @param {String} str
 * @param {String} searchString
 * @param {Number} [position= 0]
 *
 * @returns {boolean}
 */
const endsWith = (str, searchString, position) => {
  str = String(str);
  if (position === undefined || position > str.length) {
    position = str.length;
  }
  position -= searchString.length;
  const lastIndex = str.indexOf(searchString, position);
  return lastIndex !== -1 && lastIndex === position;
};


/**
 * Returns new array from array like object or null if failed
 *
 * @param {*} [thing]
 *
 * @returns {?Array}
 */
const toArray = (thing) => {
  if (!thing) return null;
  if (isArray(thing)) return thing;
  let i = thing.length;
  if (!isNumber(i)) return null;
  const arr = new Array(i);
  while (i-- > 0) {
    arr[i] = thing[i];
  }
  return arr;
};

/**
 * Checking if the Uint8Array exists and if it does, it returns a function that checks if the
 * thing passed in is an instance of Uint8Array
 *
 * @param {TypedArray}
 *
 * @returns {Array}
 */
// eslint-disable-next-line func-names
const isTypedArray = (TypedArray => {
  // eslint-disable-next-line func-names
  return thing => {
    return TypedArray && thing instanceof TypedArray;
  };
})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));

/**
 * For each entry in the object, call the function with the key and value.
 *
 * @param {Object<any, any>} obj - The object to iterate over.
 * @param {Function} fn - The function to call for each entry.
 *
 * @returns {void}
 */
const forEachEntry = (obj, fn) => {
  const generator = obj && obj[Symbol.iterator];

  const iterator = generator.call(obj);

  let result;

  while ((result = iterator.next()) && !result.done) {
    const pair = result.value;
    fn.call(obj, pair[0], pair[1]);
  }
};

/**
 * It takes a regular expression and a string, and returns an array of all the matches
 *
 * @param {string} regExp - The regular expression to match against.
 * @param {string} str - The string to search.
 *
 * @returns {Array<boolean>}
 */
const matchAll = (regExp, str) => {
  let matches;
  const arr = [];

  while ((matches = regExp.exec(str)) !== null) {
    arr.push(matches);
  }

  return arr;
};

/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
const isHTMLForm = kindOfTest('HTMLFormElement');

const toCamelCase = str => {
  return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,
    function replacer(m, p1, p2) {
      return p1.toUpperCase() + p2;
    }
  );
};

/* Creating a function that will check if an object has a property. */
const hasOwnProperty = (({hasOwnProperty}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);

/**
 * Determine if a value is a RegExp object
 *
 * @param {*} val The value to test
 *
 * @returns {boolean} True if value is a RegExp object, otherwise false
 */
const isRegExp = kindOfTest('RegExp');

const reduceDescriptors = (obj, reducer) => {
  const descriptors = Object.getOwnPropertyDescriptors(obj);
  const reducedDescriptors = {};

  forEach(descriptors, (descriptor, name) => {
    let ret;
    if ((ret = reducer(descriptor, name, obj)) !== false) {
      reducedDescriptors[name] = ret || descriptor;
    }
  });

  Object.defineProperties(obj, reducedDescriptors);
};

/**
 * Makes all methods read-only
 * @param {Object} obj
 */

const freezeMethods = (obj) => {
  reduceDescriptors(obj, (descriptor, name) => {
    // skip restricted props in strict mode
    if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {
      return false;
    }

    const value = obj[name];

    if (!isFunction(value)) return;

    descriptor.enumerable = false;

    if ('writable' in descriptor) {
      descriptor.writable = false;
      return;
    }

    if (!descriptor.set) {
      descriptor.set = () => {
        throw Error('Can not rewrite read-only method \'' + name + '\'');
      };
    }
  });
};

const toObjectSet = (arrayOrString, delimiter) => {
  const obj = {};

  const define = (arr) => {
    arr.forEach(value => {
      obj[value] = true;
    });
  };

  isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));

  return obj;
};

const noop = () => {};

const toFiniteNumber = (value, defaultValue) => {
  return value != null && Number.isFinite(value = +value) ? value : defaultValue;
};

const ALPHA = 'abcdefghijklmnopqrstuvwxyz';

const DIGIT = '0123456789';

const ALPHABET = {
  DIGIT,
  ALPHA,
  ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
};

const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
  let str = '';
  const {length} = alphabet;
  while (size--) {
    str += alphabet[Math.random() * length|0];
  }

  return str;
};

/**
 * If the thing is a FormData object, return true, otherwise return false.
 *
 * @param {unknown} thing - The thing to check.
 *
 * @returns {boolean}
 */
function isSpecCompliantForm(thing) {
  return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === 'FormData' && thing[Symbol.iterator]);
}

const toJSONObject = (obj) => {
  const stack = new Array(10);

  const visit = (source, i) => {

    if (isObject(source)) {
      if (stack.indexOf(source) >= 0) {
        return;
      }

      if(!('toJSON' in source)) {
        stack[i] = source;
        const target = isArray(source) ? [] : {};

        forEach(source, (value, key) => {
          const reducedValue = visit(value, i + 1);
          !isUndefined(reducedValue) && (target[key] = reducedValue);
        });

        stack[i] = undefined;

        return target;
      }
    }

    return source;
  };

  return visit(obj, 0);
};

const isAsyncFn = kindOfTest('AsyncFunction');

const isThenable = (thing) =>
  thing && (isObject(thing) || isFunction(thing)) && isFunction(thing.then) && isFunction(thing.catch);

var utils$1 = {
  isArray,
  isArrayBuffer,
  isBuffer,
  isFormData,
  isArrayBufferView,
  isString,
  isNumber,
  isBoolean,
  isObject,
  isPlainObject,
  isReadableStream,
  isRequest,
  isResponse,
  isHeaders,
  isUndefined,
  isDate,
  isFile,
  isBlob,
  isRegExp,
  isFunction,
  isStream,
  isURLSearchParams,
  isTypedArray,
  isFileList,
  forEach,
  merge,
  extend,
  trim,
  stripBOM,
  inherits,
  toFlatObject,
  kindOf,
  kindOfTest,
  endsWith,
  toArray,
  forEachEntry,
  matchAll,
  isHTMLForm,
  hasOwnProperty,
  hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
  reduceDescriptors,
  freezeMethods,
  toObjectSet,
  toCamelCase,
  noop,
  toFiniteNumber,
  findKey,
  global: _global,
  isContextDefined,
  ALPHABET,
  generateString,
  isSpecCompliantForm,
  toJSONObject,
  isAsyncFn,
  isThenable
};

/**
 * Create an Error with the specified message, config, error code, request and response.
 *
 * @param {string} message The error message.
 * @param {string} [code] The error code (for example, 'ECONNABORTED').
 * @param {Object} [config] The config.
 * @param {Object} [request] The request.
 * @param {Object} [response] The response.
 *
 * @returns {Error} The created error.
 */
function AxiosError(message, code, config, request, response) {
  Error.call(this);

  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, this.constructor);
  } else {
    this.stack = (new Error()).stack;
  }

  this.message = message;
  this.name = 'AxiosError';
  code && (this.code = code);
  config && (this.config = config);
  request && (this.request = request);
  response && (this.response = response);
}

utils$1.inherits(AxiosError, Error, {
  toJSON: function toJSON() {
    return {
      // Standard
      message: this.message,
      name: this.name,
      // Microsoft
      description: this.description,
      number: this.number,
      // Mozilla
      fileName: this.fileName,
      lineNumber: this.lineNumber,
      columnNumber: this.columnNumber,
      stack: this.stack,
      // Axios
      config: utils$1.toJSONObject(this.config),
      code: this.code,
      status: this.response && this.response.status ? this.response.status : null
    };
  }
});

const prototype$1 = AxiosError.prototype;
const descriptors = {};

[
  'ERR_BAD_OPTION_VALUE',
  'ERR_BAD_OPTION',
  'ECONNABORTED',
  'ETIMEDOUT',
  'ERR_NETWORK',
  'ERR_FR_TOO_MANY_REDIRECTS',
  'ERR_DEPRECATED',
  'ERR_BAD_RESPONSE',
  'ERR_BAD_REQUEST',
  'ERR_CANCELED',
  'ERR_NOT_SUPPORT',
  'ERR_INVALID_URL'
// eslint-disable-next-line func-names
].forEach(code => {
  descriptors[code] = {value: code};
});

Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype$1, 'isAxiosError', {value: true});

// eslint-disable-next-line func-names
AxiosError.from = (error, code, config, request, response, customProps) => {
  const axiosError = Object.create(prototype$1);

  utils$1.toFlatObject(error, axiosError, function filter(obj) {
    return obj !== Error.prototype;
  }, prop => {
    return prop !== 'isAxiosError';
  });

  AxiosError.call(axiosError, error.message, code, config, request, response);

  axiosError.cause = error;

  axiosError.name = error.name;

  customProps && Object.assign(axiosError, customProps);

  return axiosError;
};

// eslint-disable-next-line strict
var httpAdapter = null;

/**
 * Determines if the given thing is a array or js object.
 *
 * @param {string} thing - The object or array to be visited.
 *
 * @returns {boolean}
 */
function isVisitable(thing) {
  return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
}

/**
 * It removes the brackets from the end of a string
 *
 * @param {string} key - The key of the parameter.
 *
 * @returns {string} the key without the brackets.
 */
function removeBrackets(key) {
  return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
}

/**
 * It takes a path, a key, and a boolean, and returns a string
 *
 * @param {string} path - The path to the current key.
 * @param {string} key - The key of the current object being iterated over.
 * @param {string} dots - If true, the key will be rendered with dots instead of brackets.
 *
 * @returns {string} The path to the current key.
 */
function renderKey(path, key, dots) {
  if (!path) return key;
  return path.concat(key).map(function each(token, i) {
    // eslint-disable-next-line no-param-reassign
    token = removeBrackets(token);
    return !dots && i ? '[' + token + ']' : token;
  }).join(dots ? '.' : '');
}

/**
 * If the array is an array and none of its elements are visitable, then it's a flat array.
 *
 * @param {Array<any>} arr - The array to check
 *
 * @returns {boolean}
 */
function isFlatArray(arr) {
  return utils$1.isArray(arr) && !arr.some(isVisitable);
}

const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
  return /^is[A-Z]/.test(prop);
});

/**
 * Convert a data object to FormData
 *
 * @param {Object} obj
 * @param {?Object} [formData]
 * @param {?Object} [options]
 * @param {Function} [options.visitor]
 * @param {Boolean} [options.metaTokens = true]
 * @param {Boolean} [options.dots = false]
 * @param {?Boolean} [options.indexes = false]
 *
 * @returns {Object}
 **/

/**
 * It converts an object into a FormData object
 *
 * @param {Object<any, any>} obj - The object to convert to form data.
 * @param {string} formData - The FormData object to append to.
 * @param {Object<string, any>} options
 *
 * @returns
 */
function toFormData(obj, formData, options) {
  if (!utils$1.isObject(obj)) {
    throw new TypeError('target must be an object');
  }

  // eslint-disable-next-line no-param-reassign
  formData = formData || new (FormData)();

  // eslint-disable-next-line no-param-reassign
  options = utils$1.toFlatObject(options, {
    metaTokens: true,
    dots: false,
    indexes: false
  }, false, function defined(option, source) {
    // eslint-disable-next-line no-eq-null,eqeqeq
    return !utils$1.isUndefined(source[option]);
  });

  const metaTokens = options.metaTokens;
  // eslint-disable-next-line no-use-before-define
  const visitor = options.visitor || defaultVisitor;
  const dots = options.dots;
  const indexes = options.indexes;
  const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
  const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);

  if (!utils$1.isFunction(visitor)) {
    throw new TypeError('visitor must be a function');
  }

  function convertValue(value) {
    if (value === null) return '';

    if (utils$1.isDate(value)) {
      return value.toISOString();
    }

    if (!useBlob && utils$1.isBlob(value)) {
      throw new AxiosError('Blob is not supported. Use a Buffer instead.');
    }

    if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
      return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
    }

    return value;
  }

  /**
   * Default visitor.
   *
   * @param {*} value
   * @param {String|Number} key
   * @param {Array<String|Number>} path
   * @this {FormData}
   *
   * @returns {boolean} return true to visit the each prop of the value recursively
   */
  function defaultVisitor(value, key, path) {
    let arr = value;

    if (value && !path && typeof value === 'object') {
      if (utils$1.endsWith(key, '{}')) {
        // eslint-disable-next-line no-param-reassign
        key = metaTokens ? key : key.slice(0, -2);
        // eslint-disable-next-line no-param-reassign
        value = JSON.stringify(value);
      } else if (
        (utils$1.isArray(value) && isFlatArray(value)) ||
        ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))
        )) {
        // eslint-disable-next-line no-param-reassign
        key = removeBrackets(key);

        arr.forEach(function each(el, index) {
          !(utils$1.isUndefined(el) || el === null) && formData.append(
            // eslint-disable-next-line no-nested-ternary
            indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'),
            convertValue(el)
          );
        });
        return false;
      }
    }

    if (isVisitable(value)) {
      return true;
    }

    formData.append(renderKey(path, key, dots), convertValue(value));

    return false;
  }

  const stack = [];

  const exposedHelpers = Object.assign(predicates, {
    defaultVisitor,
    convertValue,
    isVisitable
  });

  function build(value, path) {
    if (utils$1.isUndefined(value)) return;

    if (stack.indexOf(value) !== -1) {
      throw Error('Circular reference detected in ' + path.join('.'));
    }

    stack.push(value);

    utils$1.forEach(value, function each(el, key) {
      const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(
        formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers
      );

      if (result === true) {
        build(el, path ? path.concat(key) : [key]);
      }
    });

    stack.pop();
  }

  if (!utils$1.isObject(obj)) {
    throw new TypeError('data must be an object');
  }

  build(obj);

  return formData;
}

/**
 * It encodes a string by replacing all characters that are not in the unreserved set with
 * their percent-encoded equivalents
 *
 * @param {string} str - The string to encode.
 *
 * @returns {string} The encoded string.
 */
function encode$1(str) {
  const charMap = {
    '!': '%21',
    "'": '%27',
    '(': '%28',
    ')': '%29',
    '~': '%7E',
    '%20': '+',
    '%00': '\x00'
  };
  return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
    return charMap[match];
  });
}

/**
 * It takes a params object and converts it to a FormData object
 *
 * @param {Object<string, any>} params - The parameters to be converted to a FormData object.
 * @param {Object<string, any>} options - The options object passed to the Axios constructor.
 *
 * @returns {void}
 */
function AxiosURLSearchParams(params, options) {
  this._pairs = [];

  params && toFormData(params, this, options);
}

const prototype = AxiosURLSearchParams.prototype;

prototype.append = function append(name, value) {
  this._pairs.push([name, value]);
};

prototype.toString = function toString(encoder) {
  const _encode = encoder ? function(value) {
    return encoder.call(this, value, encode$1);
  } : encode$1;

  return this._pairs.map(function each(pair) {
    return _encode(pair[0]) + '=' + _encode(pair[1]);
  }, '').join('&');
};

/**
 * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
 * URI encoded counterparts
 *
 * @param {string} val The value to be encoded.
 *
 * @returns {string} The encoded value.
 */
function encode(val) {
  return encodeURIComponent(val).
    replace(/%3A/gi, ':').
    replace(/%24/g, '$').
    replace(/%2C/gi, ',').
    replace(/%20/g, '+').
    replace(/%5B/gi, '[').
    replace(/%5D/gi, ']');
}

/**
 * Build a URL by appending params to the end
 *
 * @param {string} url The base of the url (e.g., http://www.google.com)
 * @param {object} [params] The params to be appended
 * @param {?object} options
 *
 * @returns {string} The formatted url
 */
function buildURL(url, params, options) {
  /*eslint no-param-reassign:0*/
  if (!params) {
    return url;
  }
  
  const _encode = options && options.encode || encode;

  const serializeFn = options && options.serialize;

  let serializedParams;

  if (serializeFn) {
    serializedParams = serializeFn(params, options);
  } else {
    serializedParams = utils$1.isURLSearchParams(params) ?
      params.toString() :
      new AxiosURLSearchParams(params, options).toString(_encode);
  }

  if (serializedParams) {
    const hashmarkIndex = url.indexOf("#");

    if (hashmarkIndex !== -1) {
      url = url.slice(0, hashmarkIndex);
    }
    url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  }

  return url;
}

class InterceptorManager {
  constructor() {
    this.handlers = [];
  }

  /**
   * Add a new interceptor to the stack
   *
   * @param {Function} fulfilled The function to handle `then` for a `Promise`
   * @param {Function} rejected The function to handle `reject` for a `Promise`
   *
   * @return {Number} An ID used to remove interceptor later
   */
  use(fulfilled, rejected, options) {
    this.handlers.push({
      fulfilled,
      rejected,
      synchronous: options ? options.synchronous : false,
      runWhen: options ? options.runWhen : null
    });
    return this.handlers.length - 1;
  }

  /**
   * Remove an interceptor from the stack
   *
   * @param {Number} id The ID that was returned by `use`
   *
   * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
   */
  eject(id) {
    if (this.handlers[id]) {
      this.handlers[id] = null;
    }
  }

  /**
   * Clear all interceptors from the stack
   *
   * @returns {void}
   */
  clear() {
    if (this.handlers) {
      this.handlers = [];
    }
  }

  /**
   * Iterate over all the registered interceptors
   *
   * This method is particularly useful for skipping over any
   * interceptors that may have become `null` calling `eject`.
   *
   * @param {Function} fn The function to call for each interceptor
   *
   * @returns {void}
   */
  forEach(fn) {
    utils$1.forEach(this.handlers, function forEachHandler(h) {
      if (h !== null) {
        fn(h);
      }
    });
  }
}

var transitionalDefaults = {
  silentJSONParsing: true,
  forcedJSONParsing: true,
  clarifyTimeoutError: false
};

var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;

var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;

var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;

var platform$1 = {
  isBrowser: true,
  classes: {
    URLSearchParams: URLSearchParams$1,
    FormData: FormData$1,
    Blob: Blob$1
  },
  protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
};

const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';

/**
 * Determine if we're running in a standard browser environment
 *
 * This allows axios to run in a web worker, and react-native.
 * Both environments support XMLHttpRequest, but not fully standard globals.
 *
 * web workers:
 *  typeof window -> undefined
 *  typeof document -> undefined
 *
 * react-native:
 *  navigator.product -> 'ReactNative'
 * nativescript
 *  navigator.product -> 'NativeScript' or 'NS'
 *
 * @returns {boolean}
 */
const hasStandardBrowserEnv = (
  (product) => {
    return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0
  })(typeof navigator !== 'undefined' && navigator.product);

/**
 * Determine if we're running in a standard browser webWorker environment
 *
 * Although the `isStandardBrowserEnv` method indicates that
 * `allows axios to run in a web worker`, the WebWorker will still be
 * filtered out due to its judgment standard
 * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
 * This leads to a problem when axios post `FormData` in webWorker
 */
const hasStandardBrowserWebWorkerEnv = (() => {
  return (
    typeof WorkerGlobalScope !== 'undefined' &&
    // eslint-disable-next-line no-undef
    self instanceof WorkerGlobalScope &&
    typeof self.importScripts === 'function'
  );
})();

const origin = hasBrowserEnv && window.location.href || 'http://localhost';

var utils = /*#__PURE__*/Object.freeze({
  __proto__: null,
  hasBrowserEnv: hasBrowserEnv,
  hasStandardBrowserEnv: hasStandardBrowserEnv,
  hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
  origin: origin
});

var platform = {
  ...utils,
  ...platform$1
};

function toURLEncodedForm(data, options) {
  return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
    visitor: function(value, key, path, helpers) {
      if (platform.isNode && utils$1.isBuffer(value)) {
        this.append(key, value.toString('base64'));
        return false;
      }

      return helpers.defaultVisitor.apply(this, arguments);
    }
  }, options));
}

/**
 * It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
 *
 * @param {string} name - The name of the property to get.
 *
 * @returns An array of strings.
 */
function parsePropPath(name) {
  // foo[x][y][z]
  // foo.x.y.z
  // foo-x-y-z
  // foo x y z
  return utils$1.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
    return match[0] === '[]' ? '' : match[1] || match[0];
  });
}

/**
 * Convert an array to an object.
 *
 * @param {Array<any>} arr - The array to convert to an object.
 *
 * @returns An object with the same keys and values as the array.
 */
function arrayToObject(arr) {
  const obj = {};
  const keys = Object.keys(arr);
  let i;
  const len = keys.length;
  let key;
  for (i = 0; i < len; i++) {
    key = keys[i];
    obj[key] = arr[key];
  }
  return obj;
}

/**
 * It takes a FormData object and returns a JavaScript object
 *
 * @param {string} formData The FormData object to convert to JSON.
 *
 * @returns {Object<string, any> | null} The converted object.
 */
function formDataToJSON(formData) {
  function buildPath(path, value, target, index) {
    let name = path[index++];

    if (name === '__proto__') return true;

    const isNumericKey = Number.isFinite(+name);
    const isLast = index >= path.length;
    name = !name && utils$1.isArray(target) ? target.length : name;

    if (isLast) {
      if (utils$1.hasOwnProp(target, name)) {
        target[name] = [target[name], value];
      } else {
        target[name] = value;
      }

      return !isNumericKey;
    }

    if (!target[name] || !utils$1.isObject(target[name])) {
      target[name] = [];
    }

    const result = buildPath(path, value, target[name], index);

    if (result && utils$1.isArray(target[name])) {
      target[name] = arrayToObject(target[name]);
    }

    return !isNumericKey;
  }

  if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
    const obj = {};

    utils$1.forEachEntry(formData, (name, value) => {
      buildPath(parsePropPath(name), value, obj, 0);
    });

    return obj;
  }

  return null;
}

/**
 * It takes a string, tries to parse it, and if it fails, it returns the stringified version
 * of the input
 *
 * @param {any} rawValue - The value to be stringified.
 * @param {Function} parser - A function that parses a string into a JavaScript object.
 * @param {Function} encoder - A function that takes a value and returns a string.
 *
 * @returns {string} A stringified version of the rawValue.
 */
function stringifySafely(rawValue, parser, encoder) {
  if (utils$1.isString(rawValue)) {
    try {
      (parser || JSON.parse)(rawValue);
      return utils$1.trim(rawValue);
    } catch (e) {
      if (e.name !== 'SyntaxError') {
        throw e;
      }
    }
  }

  return (encoder || JSON.stringify)(rawValue);
}

const defaults = {

  transitional: transitionalDefaults,

  adapter: ['xhr', 'http', 'fetch'],

  transformRequest: [function transformRequest(data, headers) {
    const contentType = headers.getContentType() || '';
    const hasJSONContentType = contentType.indexOf('application/json') > -1;
    const isObjectPayload = utils$1.isObject(data);

    if (isObjectPayload && utils$1.isHTMLForm(data)) {
      data = new FormData(data);
    }

    const isFormData = utils$1.isFormData(data);

    if (isFormData) {
      return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
    }

    if (utils$1.isArrayBuffer(data) ||
      utils$1.isBuffer(data) ||
      utils$1.isStream(data) ||
      utils$1.isFile(data) ||
      utils$1.isBlob(data) ||
      utils$1.isReadableStream(data)
    ) {
      return data;
    }
    if (utils$1.isArrayBufferView(data)) {
      return data.buffer;
    }
    if (utils$1.isURLSearchParams(data)) {
      headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
      return data.toString();
    }

    let isFileList;

    if (isObjectPayload) {
      if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
        return toURLEncodedForm(data, this.formSerializer).toString();
      }

      if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
        const _FormData = this.env && this.env.FormData;

        return toFormData(
          isFileList ? {'files[]': data} : data,
          _FormData && new _FormData(),
          this.formSerializer
        );
      }
    }

    if (isObjectPayload || hasJSONContentType ) {
      headers.setContentType('application/json', false);
      return stringifySafely(data);
    }

    return data;
  }],

  transformResponse: [function transformResponse(data) {
    const transitional = this.transitional || defaults.transitional;
    const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
    const JSONRequested = this.responseType === 'json';

    if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
      return data;
    }

    if (data && utils$1.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
      const silentJSONParsing = transitional && transitional.silentJSONParsing;
      const strictJSONParsing = !silentJSONParsing && JSONRequested;

      try {
        return JSON.parse(data);
      } catch (e) {
        if (strictJSONParsing) {
          if (e.name === 'SyntaxError') {
            throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
          }
          throw e;
        }
      }
    }

    return data;
  }],

  /**
   * A timeout in milliseconds to abort a request. If set to 0 (default) a
   * timeout is not created.
   */
  timeout: 0,

  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',

  maxContentLength: -1,
  maxBodyLength: -1,

  env: {
    FormData: platform.classes.FormData,
    Blob: platform.classes.Blob
  },

  validateStatus: function validateStatus(status) {
    return status >= 200 && status < 300;
  },

  headers: {
    common: {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': undefined
    }
  }
};

utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
  defaults.headers[method] = {};
});

// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
const ignoreDuplicateOf = utils$1.toObjectSet([
  'age', 'authorization', 'content-length', 'content-type', 'etag',
  'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  'referer', 'retry-after', 'user-agent'
]);

/**
 * Parse headers into an object
 *
 * ```
 * Date: Wed, 27 Aug 2014 08:58:49 GMT
 * Content-Type: application/json
 * Connection: keep-alive
 * Transfer-Encoding: chunked
 * ```
 *
 * @param {String} rawHeaders Headers needing to be parsed
 *
 * @returns {Object} Headers parsed into an object
 */
var parseHeaders = rawHeaders => {
  const parsed = {};
  let key;
  let val;
  let i;

  rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
    i = line.indexOf(':');
    key = line.substring(0, i).trim().toLowerCase();
    val = line.substring(i + 1).trim();

    if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
      return;
    }

    if (key === 'set-cookie') {
      if (parsed[key]) {
        parsed[key].push(val);
      } else {
        parsed[key] = [val];
      }
    } else {
      parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
    }
  });

  return parsed;
};

const $internals = Symbol('internals');

function normalizeHeader(header) {
  return header && String(header).trim().toLowerCase();
}

function normalizeValue(value) {
  if (value === false || value == null) {
    return value;
  }

  return utils$1.isArray(value) ? value.map(normalizeValue) : String(value);
}

function parseTokens(str) {
  const tokens = Object.create(null);
  const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  let match;

  while ((match = tokensRE.exec(str))) {
    tokens[match[1]] = match[2];
  }

  return tokens;
}

const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());

function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
  if (utils$1.isFunction(filter)) {
    return filter.call(this, value, header);
  }

  if (isHeaderNameFilter) {
    value = header;
  }

  if (!utils$1.isString(value)) return;

  if (utils$1.isString(filter)) {
    return value.indexOf(filter) !== -1;
  }

  if (utils$1.isRegExp(filter)) {
    return filter.test(value);
  }
}

function formatHeader(header) {
  return header.trim()
    .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
      return char.toUpperCase() + str;
    });
}

function buildAccessors(obj, header) {
  const accessorName = utils$1.toCamelCase(' ' + header);

  ['get', 'set', 'has'].forEach(methodName => {
    Object.defineProperty(obj, methodName + accessorName, {
      value: function(arg1, arg2, arg3) {
        return this[methodName].call(this, header, arg1, arg2, arg3);
      },
      configurable: true
    });
  });
}

class AxiosHeaders {
  constructor(headers) {
    headers && this.set(headers);
  }

  set(header, valueOrRewrite, rewrite) {
    const self = this;

    function setHeader(_value, _header, _rewrite) {
      const lHeader = normalizeHeader(_header);

      if (!lHeader) {
        throw new Error('header name must be a non-empty string');
      }

      const key = utils$1.findKey(self, lHeader);

      if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
        self[key || _header] = normalizeValue(_value);
      }
    }

    const setHeaders = (headers, _rewrite) =>
      utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));

    if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
      setHeaders(header, valueOrRewrite);
    } else if(utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
      setHeaders(parseHeaders(header), valueOrRewrite);
    } else if (utils$1.isHeaders(header)) {
      for (const [key, value] of header.entries()) {
        setHeader(value, key, rewrite);
      }
    } else {
      header != null && setHeader(valueOrRewrite, header, rewrite);
    }

    return this;
  }

  get(header, parser) {
    header = normalizeHeader(header);

    if (header) {
      const key = utils$1.findKey(this, header);

      if (key) {
        const value = this[key];

        if (!parser) {
          return value;
        }

        if (parser === true) {
          return parseTokens(value);
        }

        if (utils$1.isFunction(parser)) {
          return parser.call(this, value, key);
        }

        if (utils$1.isRegExp(parser)) {
          return parser.exec(value);
        }

        throw new TypeError('parser must be boolean|regexp|function');
      }
    }
  }

  has(header, matcher) {
    header = normalizeHeader(header);

    if (header) {
      const key = utils$1.findKey(this, header);

      return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
    }

    return false;
  }

  delete(header, matcher) {
    const self = this;
    let deleted = false;

    function deleteHeader(_header) {
      _header = normalizeHeader(_header);

      if (_header) {
        const key = utils$1.findKey(self, _header);

        if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
          delete self[key];

          deleted = true;
        }
      }
    }

    if (utils$1.isArray(header)) {
      header.forEach(deleteHeader);
    } else {
      deleteHeader(header);
    }

    return deleted;
  }

  clear(matcher) {
    const keys = Object.keys(this);
    let i = keys.length;
    let deleted = false;

    while (i--) {
      const key = keys[i];
      if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
        delete this[key];
        deleted = true;
      }
    }

    return deleted;
  }

  normalize(format) {
    const self = this;
    const headers = {};

    utils$1.forEach(this, (value, header) => {
      const key = utils$1.findKey(headers, header);

      if (key) {
        self[key] = normalizeValue(value);
        delete self[header];
        return;
      }

      const normalized = format ? formatHeader(header) : String(header).trim();

      if (normalized !== header) {
        delete self[header];
      }

      self[normalized] = normalizeValue(value);

      headers[normalized] = true;
    });

    return this;
  }

  concat(...targets) {
    return this.constructor.concat(this, ...targets);
  }

  toJSON(asStrings) {
    const obj = Object.create(null);

    utils$1.forEach(this, (value, header) => {
      value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
    });

    return obj;
  }

  [Symbol.iterator]() {
    return Object.entries(this.toJSON())[Symbol.iterator]();
  }

  toString() {
    return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
  }

  get [Symbol.toStringTag]() {
    return 'AxiosHeaders';
  }

  static from(thing) {
    return thing instanceof this ? thing : new this(thing);
  }

  static concat(first, ...targets) {
    const computed = new this(first);

    targets.forEach((target) => computed.set(target));

    return computed;
  }

  static accessor(header) {
    const internals = this[$internals] = (this[$internals] = {
      accessors: {}
    });

    const accessors = internals.accessors;
    const prototype = this.prototype;

    function defineAccessor(_header) {
      const lHeader = normalizeHeader(_header);

      if (!accessors[lHeader]) {
        buildAccessors(prototype, _header);
        accessors[lHeader] = true;
      }
    }

    utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);

    return this;
  }
}

AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);

// reserved names hotfix
utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
  let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
  return {
    get: () => value,
    set(headerValue) {
      this[mapped] = headerValue;
    }
  }
});

utils$1.freezeMethods(AxiosHeaders);

/**
 * Transform the data for a request or a response
 *
 * @param {Array|Function} fns A single function or Array of functions
 * @param {?Object} response The response object
 *
 * @returns {*} The resulting transformed data
 */
function transformData(fns, response) {
  const config = this || defaults;
  const context = response || config;
  const headers = AxiosHeaders.from(context.headers);
  let data = context.data;

  utils$1.forEach(fns, function transform(fn) {
    data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
  });

  headers.normalize();

  return data;
}

function isCancel(value) {
  return !!(value && value.__CANCEL__);
}

/**
 * A `CanceledError` is an object that is thrown when an operation is canceled.
 *
 * @param {string=} message The message.
 * @param {Object=} config The config.
 * @param {Object=} request The request.
 *
 * @returns {CanceledError} The created error.
 */
function CanceledError(message, config, request) {
  // eslint-disable-next-line no-eq-null,eqeqeq
  AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
  this.name = 'CanceledError';
}

utils$1.inherits(CanceledError, AxiosError, {
  __CANCEL__: true
});

/**
 * Resolve or reject a Promise based on response status.
 *
 * @param {Function} resolve A function that resolves the promise.
 * @param {Function} reject A function that rejects the promise.
 * @param {object} response The response.
 *
 * @returns {object} The response.
 */
function settle(resolve, reject, response) {
  const validateStatus = response.config.validateStatus;
  if (!response.status || !validateStatus || validateStatus(response.status)) {
    resolve(response);
  } else {
    reject(new AxiosError(
      'Request failed with status code ' + response.status,
      [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
      response.config,
      response.request,
      response
    ));
  }
}

function parseProtocol(url) {
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
  return match && match[1] || '';
}

/**
 * Calculate data maxRate
 * @param {Number} [samplesCount= 10]
 * @param {Number} [min= 1000]
 * @returns {Function}
 */
function speedometer(samplesCount, min) {
  samplesCount = samplesCount || 10;
  const bytes = new Array(samplesCount);
  const timestamps = new Array(samplesCount);
  let head = 0;
  let tail = 0;
  let firstSampleTS;

  min = min !== undefined ? min : 1000;

  return function push(chunkLength) {
    const now = Date.now();

    const startedAt = timestamps[tail];

    if (!firstSampleTS) {
      firstSampleTS = now;
    }

    bytes[head] = chunkLength;
    timestamps[head] = now;

    let i = tail;
    let bytesCount = 0;

    while (i !== head) {
      bytesCount += bytes[i++];
      i = i % samplesCount;
    }

    head = (head + 1) % samplesCount;

    if (head === tail) {
      tail = (tail + 1) % samplesCount;
    }

    if (now - firstSampleTS < min) {
      return;
    }

    const passed = startedAt && now - startedAt;

    return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
  };
}

/**
 * Throttle decorator
 * @param {Function} fn
 * @param {Number} freq
 * @return {Function}
 */
function throttle(fn, freq) {
  let timestamp = 0;
  const threshold = 1000 / freq;
  let timer = null;
  return function throttled() {
    const force = this === true;

    const now = Date.now();
    if (force || now - timestamp > threshold) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      timestamp = now;
      return fn.apply(null, arguments);
    }
    if (!timer) {
      timer = setTimeout(() => {
        timer = null;
        timestamp = Date.now();
        return fn.apply(null, arguments);
      }, threshold - (now - timestamp));
    }
  };
}

var progressEventReducer = (listener, isDownloadStream, freq = 3) => {
  let bytesNotified = 0;
  const _speedometer = speedometer(50, 250);

  return throttle(e => {
    const loaded = e.loaded;
    const total = e.lengthComputable ? e.total : undefined;
    const progressBytes = loaded - bytesNotified;
    const rate = _speedometer(progressBytes);
    const inRange = loaded <= total;

    bytesNotified = loaded;

    const data = {
      loaded,
      total,
      progress: total ? (loaded / total) : undefined,
      bytes: progressBytes,
      rate: rate ? rate : undefined,
      estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
      event: e,
      lengthComputable: total != null
    };

    data[isDownloadStream ? 'download' : 'upload'] = true;

    listener(data);
  }, freq);
};

var isURLSameOrigin = platform.hasStandardBrowserEnv ?

// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
  (function standardBrowserEnv() {
    const msie = /(msie|trident)/i.test(navigator.userAgent);
    const urlParsingNode = document.createElement('a');
    let originURL;

    /**
    * Parse a URL to discover its components
    *
    * @param {String} url The URL to be parsed
    * @returns {Object}
    */
    function resolveURL(url) {
      let href = url;

      if (msie) {
        // IE needs attribute set twice to normalize properties
        urlParsingNode.setAttribute('href', href);
        href = urlParsingNode.href;
      }

      urlParsingNode.setAttribute('href', href);

      // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
      return {
        href: urlParsingNode.href,
        protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
        host: urlParsingNode.host,
        search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
        hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
        hostname: urlParsingNode.hostname,
        port: urlParsingNode.port,
        pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
          urlParsingNode.pathname :
          '/' + urlParsingNode.pathname
      };
    }

    originURL = resolveURL(window.location.href);

    /**
    * Determine if a URL shares the same origin as the current location
    *
    * @param {String} requestURL The URL to test
    * @returns {boolean} True if URL shares the same origin, otherwise false
    */
    return function isURLSameOrigin(requestURL) {
      const parsed = (utils$1.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
      return (parsed.protocol === originURL.protocol &&
          parsed.host === originURL.host);
    };
  })() :

  // Non standard browser envs (web workers, react-native) lack needed support.
  (function nonStandardBrowserEnv() {
    return function isURLSameOrigin() {
      return true;
    };
  })();

var cookies = platform.hasStandardBrowserEnv ?

  // Standard browser envs support document.cookie
  {
    write(name, value, expires, path, domain, secure) {
      const cookie = [name + '=' + encodeURIComponent(value)];

      utils$1.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());

      utils$1.isString(path) && cookie.push('path=' + path);

      utils$1.isString(domain) && cookie.push('domain=' + domain);

      secure === true && cookie.push('secure');

      document.cookie = cookie.join('; ');
    },

    read(name) {
      const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
      return (match ? decodeURIComponent(match[3]) : null);
    },

    remove(name) {
      this.write(name, '', Date.now() - 86400000);
    }
  }

  :

  // Non-standard browser env (web workers, react-native) lack needed support.
  {
    write() {},
    read() {
      return null;
    },
    remove() {}
  };

/**
 * Determines whether the specified URL is absolute
 *
 * @param {string} url The URL to test
 *
 * @returns {boolean} True if the specified URL is absolute, otherwise false
 */
function isAbsoluteURL(url) {
  // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  // by any combination of letters, digits, plus, period, or hyphen.
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}

/**
 * Creates a new URL by combining the specified URLs
 *
 * @param {string} baseURL The base URL
 * @param {string} relativeURL The relative URL
 *
 * @returns {string} The combined URL
 */
function combineURLs(baseURL, relativeURL) {
  return relativeURL
    ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
    : baseURL;
}

/**
 * Creates a new URL by combining the baseURL with the requestedURL,
 * only when the requestedURL is not already an absolute URL.
 * If the requestURL is absolute, this function returns the requestedURL untouched.
 *
 * @param {string} baseURL The base URL
 * @param {string} requestedURL Absolute or relative URL to combine
 *
 * @returns {string} The combined full path
 */
function buildFullPath(baseURL, requestedURL) {
  if (baseURL && !isAbsoluteURL(requestedURL)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
}

const headersToObject = (thing) => thing instanceof AxiosHeaders ? { ...thing } : thing;

/**
 * Config-specific merge-function which creates a new config-object
 * by merging two configuration objects together.
 *
 * @param {Object} config1
 * @param {Object} config2
 *
 * @returns {Object} New object resulting from merging config2 to config1
 */
function mergeConfig(config1, config2) {
  // eslint-disable-next-line no-param-reassign
  config2 = config2 || {};
  const config = {};

  function getMergedValue(target, source, caseless) {
    if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
      return utils$1.merge.call({caseless}, target, source);
    } else if (utils$1.isPlainObject(source)) {
      return utils$1.merge({}, source);
    } else if (utils$1.isArray(source)) {
      return source.slice();
    }
    return source;
  }

  // eslint-disable-next-line consistent-return
  function mergeDeepProperties(a, b, caseless) {
    if (!utils$1.isUndefined(b)) {
      return getMergedValue(a, b, caseless);
    } else if (!utils$1.isUndefined(a)) {
      return getMergedValue(undefined, a, caseless);
    }
  }

  // eslint-disable-next-line consistent-return
  function valueFromConfig2(a, b) {
    if (!utils$1.isUndefined(b)) {
      return getMergedValue(undefined, b);
    }
  }

  // eslint-disable-next-line consistent-return
  function defaultToConfig2(a, b) {
    if (!utils$1.isUndefined(b)) {
      return getMergedValue(undefined, b);
    } else if (!utils$1.isUndefined(a)) {
      return getMergedValue(undefined, a);
    }
  }

  // eslint-disable-next-line consistent-return
  function mergeDirectKeys(a, b, prop) {
    if (prop in config2) {
      return getMergedValue(a, b);
    } else if (prop in config1) {
      return getMergedValue(undefined, a);
    }
  }

  const mergeMap = {
    url: valueFromConfig2,
    method: valueFromConfig2,
    data: valueFromConfig2,
    baseURL: defaultToConfig2,
    transformRequest: defaultToConfig2,
    transformResponse: defaultToConfig2,
    paramsSerializer: defaultToConfig2,
    timeout: defaultToConfig2,
    timeoutMessage: defaultToConfig2,
    withCredentials: defaultToConfig2,
    withXSRFToken: defaultToConfig2,
    adapter: defaultToConfig2,
    responseType: defaultToConfig2,
    xsrfCookieName: defaultToConfig2,
    xsrfHeaderName: defaultToConfig2,
    onUploadProgress: defaultToConfig2,
    onDownloadProgress: defaultToConfig2,
    decompress: defaultToConfig2,
    maxContentLength: defaultToConfig2,
    maxBodyLength: defaultToConfig2,
    beforeRedirect: defaultToConfig2,
    transport: defaultToConfig2,
    httpAgent: defaultToConfig2,
    httpsAgent: defaultToConfig2,
    cancelToken: defaultToConfig2,
    socketPath: defaultToConfig2,
    responseEncoding: defaultToConfig2,
    validateStatus: mergeDirectKeys,
    headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
  };

  utils$1.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
    const merge = mergeMap[prop] || mergeDeepProperties;
    const configValue = merge(config1[prop], config2[prop], prop);
    (utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
  });

  return config;
}

var resolveConfig = (config) => {
  const newConfig = mergeConfig({}, config);

  let {data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth} = newConfig;

  newConfig.headers = headers = AxiosHeaders.from(headers);

  newConfig.url = buildURL(buildFullPath(newConfig.baseURL, newConfig.url), config.params, config.paramsSerializer);

  // HTTP basic authentication
  if (auth) {
    headers.set('Authorization', 'Basic ' +
      btoa((auth.username || '') + ':' + (auth.password ? unescape(encodeURIComponent(auth.password)) : ''))
    );
  }

  let contentType;

  if (utils$1.isFormData(data)) {
    if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
      headers.setContentType(undefined); // Let the browser set it
    } else if ((contentType = headers.getContentType()) !== false) {
      // fix semicolon duplication issue for ReactNative FormData implementation
      const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
      headers.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
    }
  }

  // Add xsrf header
  // This is only done if running in a standard browser environment.
  // Specifically not if we're in a web worker, or react-native.

  if (platform.hasStandardBrowserEnv) {
    withXSRFToken && utils$1.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));

    if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(newConfig.url))) {
      // Add xsrf header
      const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);

      if (xsrfValue) {
        headers.set(xsrfHeaderName, xsrfValue);
      }
    }
  }

  return newConfig;
};

const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';

var xhrAdapter = isXHRAdapterSupported && function (config) {
  return new Promise(function dispatchXhrRequest(resolve, reject) {
    const _config = resolveConfig(config);
    let requestData = _config.data;
    const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
    let {responseType} = _config;
    let onCanceled;
    function done() {
      if (_config.cancelToken) {
        _config.cancelToken.unsubscribe(onCanceled);
      }

      if (_config.signal) {
        _config.signal.removeEventListener('abort', onCanceled);
      }
    }

    let request = new XMLHttpRequest();

    request.open(_config.method.toUpperCase(), _config.url, true);

    // Set the request timeout in MS
    request.timeout = _config.timeout;

    function onloadend() {
      if (!request) {
        return;
      }
      // Prepare the response
      const responseHeaders = AxiosHeaders.from(
        'getAllResponseHeaders' in request && request.getAllResponseHeaders()
      );
      const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
        request.responseText : request.response;
      const response = {
        data: responseData,
        status: request.status,
        statusText: request.statusText,
        headers: responseHeaders,
        config,
        request
      };

      settle(function _resolve(value) {
        resolve(value);
        done();
      }, function _reject(err) {
        reject(err);
        done();
      }, response);

      // Clean up request
      request = null;
    }

    if ('onloadend' in request) {
      // Use onloadend if available
      request.onloadend = onloadend;
    } else {
      // Listen for ready state to emulate onloadend
      request.onreadystatechange = function handleLoad() {
        if (!request || request.readyState !== 4) {
          return;
        }

        // The request errored out and we didn't get a response, this will be
        // handled by onerror instead
        // With one exception: request that using file: protocol, most browsers
        // will return status as 0 even though it's a successful request
        if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
          return;
        }
        // readystate handler is calling before onerror or ontimeout handlers,
        // so we should call onloadend on the next 'tick'
        setTimeout(onloadend);
      };
    }

    // Handle browser request cancellation (as opposed to a manual cancellation)
    request.onabort = function handleAbort() {
      if (!request) {
        return;
      }

      reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, _config, request));

      // Clean up request
      request = null;
    };

    // Handle low level network errors
    request.onerror = function handleError() {
      // Real errors are hidden from us by the browser
      // onerror should only fire if it's a network error
      reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, _config, request));

      // Clean up request
      request = null;
    };

    // Handle timeout
    request.ontimeout = function handleTimeout() {
      let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
      const transitional = _config.transitional || transitionalDefaults;
      if (_config.timeoutErrorMessage) {
        timeoutErrorMessage = _config.timeoutErrorMessage;
      }
      reject(new AxiosError(
        timeoutErrorMessage,
        transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
        _config,
        request));

      // Clean up request
      request = null;
    };

    // Remove Content-Type if data is undefined
    requestData === undefined && requestHeaders.setContentType(null);

    // Add headers to the request
    if ('setRequestHeader' in request) {
      utils$1.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
        request.setRequestHeader(key, val);
      });
    }

    // Add withCredentials to request if needed
    if (!utils$1.isUndefined(_config.withCredentials)) {
      request.withCredentials = !!_config.withCredentials;
    }

    // Add responseType to request if needed
    if (responseType && responseType !== 'json') {
      request.responseType = _config.responseType;
    }

    // Handle progress if needed
    if (typeof _config.onDownloadProgress === 'function') {
      request.addEventListener('progress', progressEventReducer(_config.onDownloadProgress, true));
    }

    // Not all browsers support upload events
    if (typeof _config.onUploadProgress === 'function' && request.upload) {
      request.upload.addEventListener('progress', progressEventReducer(_config.onUploadProgress));
    }

    if (_config.cancelToken || _config.signal) {
      // Handle cancellation
      // eslint-disable-next-line func-names
      onCanceled = cancel => {
        if (!request) {
          return;
        }
        reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
        request.abort();
        request = null;
      };

      _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
      if (_config.signal) {
        _config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
      }
    }

    const protocol = parseProtocol(_config.url);

    if (protocol && platform.protocols.indexOf(protocol) === -1) {
      reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
      return;
    }


    // Send the request
    request.send(requestData || null);
  });
};

const composeSignals = (signals, timeout) => {
  let controller = new AbortController();

  let aborted;

  const onabort = function (cancel) {
    if (!aborted) {
      aborted = true;
      unsubscribe();
      const err = cancel instanceof Error ? cancel : this.reason;
      controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
    }
  };

  let timer = timeout && setTimeout(() => {
    onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT));
  }, timeout);

  const unsubscribe = () => {
    if (signals) {
      timer && clearTimeout(timer);
      timer = null;
      signals.forEach(signal => {
        signal &&
        (signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort));
      });
      signals = null;
    }
  };

  signals.forEach((signal) => signal && signal.addEventListener && signal.addEventListener('abort', onabort));

  const {signal} = controller;

  signal.unsubscribe = unsubscribe;

  return [signal, () => {
    timer && clearTimeout(timer);
    timer = null;
  }];
};

const streamChunk = function* (chunk, chunkSize) {
  let len = chunk.byteLength;

  if (!chunkSize || len < chunkSize) {
    yield chunk;
    return;
  }

  let pos = 0;
  let end;

  while (pos < len) {
    end = pos + chunkSize;
    yield chunk.slice(pos, end);
    pos = end;
  }
};

const readBytes = async function* (iterable, chunkSize, encode) {
  for await (const chunk of iterable) {
    yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encode(String(chunk))), chunkSize);
  }
};

const trackStream = (stream, chunkSize, onProgress, onFinish, encode) => {
  const iterator = readBytes(stream, chunkSize, encode);

  let bytes = 0;

  return new ReadableStream({
    type: 'bytes',

    async pull(controller) {
      const {done, value} = await iterator.next();

      if (done) {
        controller.close();
        onFinish();
        return;
      }

      let len = value.byteLength;
      onProgress && onProgress(bytes += len);
      controller.enqueue(new Uint8Array(value));
    },
    cancel(reason) {
      onFinish(reason);
      return iterator.return();
    }
  }, {
    highWaterMark: 2
  })
};

const fetchProgressDecorator = (total, fn) => {
  const lengthComputable = total != null;
  return (loaded) => setTimeout(() => fn({
    lengthComputable,
    total,
    loaded
  }));
};

const isFetchSupported = typeof fetch === 'function' && typeof Request === 'function' && typeof Response === 'function';
const isReadableStreamSupported = isFetchSupported && typeof ReadableStream === 'function';

// used only inside the fetch adapter
const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ?
    ((encoder) => (str) => encoder.encode(str))(new TextEncoder()) :
    async (str) => new Uint8Array(await new Response(str).arrayBuffer())
);

const supportsRequestStream = isReadableStreamSupported && (() => {
  let duplexAccessed = false;

  const hasContentType = new Request(platform.origin, {
    body: new ReadableStream(),
    method: 'POST',
    get duplex() {
      duplexAccessed = true;
      return 'half';
    },
  }).headers.has('Content-Type');

  return duplexAccessed && !hasContentType;
})();

const DEFAULT_CHUNK_SIZE = 64 * 1024;

const supportsResponseStream = isReadableStreamSupported && !!(()=> {
  try {
    return utils$1.isReadableStream(new Response('').body);
  } catch(err) {
    // return undefined
  }
})();

const resolvers = {
  stream: supportsResponseStream && ((res) => res.body)
};

isFetchSupported && (((res) => {
  ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
    !resolvers[type] && (resolvers[type] = utils$1.isFunction(res[type]) ? (res) => res[type]() :
      (_, config) => {
        throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
      });
  });
})(new Response));

const getBodyLength = async (body) => {
  if (body == null) {
    return 0;
  }

  if(utils$1.isBlob(body)) {
    return body.size;
  }

  if(utils$1.isSpecCompliantForm(body)) {
    return (await new Request(body).arrayBuffer()).byteLength;
  }

  if(utils$1.isArrayBufferView(body)) {
    return body.byteLength;
  }

  if(utils$1.isURLSearchParams(body)) {
    body = body + '';
  }

  if(utils$1.isString(body)) {
    return (await encodeText(body)).byteLength;
  }
};

const resolveBodyLength = async (headers, body) => {
  const length = utils$1.toFiniteNumber(headers.getContentLength());

  return length == null ? getBodyLength(body) : length;
};

var fetchAdapter = isFetchSupported && (async (config) => {
  let {
    url,
    method,
    data,
    signal,
    cancelToken,
    timeout,
    onDownloadProgress,
    onUploadProgress,
    responseType,
    headers,
    withCredentials = 'same-origin',
    fetchOptions
  } = resolveConfig(config);

  responseType = responseType ? (responseType + '').toLowerCase() : 'text';

  let [composedSignal, stopTimeout] = (signal || cancelToken || timeout) ?
    composeSignals([signal, cancelToken], timeout) : [];

  let finished, request;

  const onFinish = () => {
    !finished && setTimeout(() => {
      composedSignal && composedSignal.unsubscribe();
    });

    finished = true;
  };

  let requestContentLength;

  try {
    if (
      onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head' &&
      (requestContentLength = await resolveBodyLength(headers, data)) !== 0
    ) {
      let _request = new Request(url, {
        method: 'POST',
        body: data,
        duplex: "half"
      });

      let contentTypeHeader;

      if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
        headers.setContentType(contentTypeHeader);
      }

      if (_request.body) {
        data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, fetchProgressDecorator(
          requestContentLength,
          progressEventReducer(onUploadProgress)
        ), null, encodeText);
      }
    }

    if (!utils$1.isString(withCredentials)) {
      withCredentials = withCredentials ? 'cors' : 'omit';
    }

    request = new Request(url, {
      ...fetchOptions,
      signal: composedSignal,
      method: method.toUpperCase(),
      headers: headers.normalize().toJSON(),
      body: data,
      duplex: "half",
      withCredentials
    });

    let response = await fetch(request);

    const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');

    if (supportsResponseStream && (onDownloadProgress || isStreamResponse)) {
      const options = {};

      ['status', 'statusText', 'headers'].forEach(prop => {
        options[prop] = response[prop];
      });

      const responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));

      response = new Response(
        trackStream(response.body, DEFAULT_CHUNK_SIZE, onDownloadProgress && fetchProgressDecorator(
          responseContentLength,
          progressEventReducer(onDownloadProgress, true)
        ), isStreamResponse && onFinish, encodeText),
        options
      );
    }

    responseType = responseType || 'text';

    let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);

    !isStreamResponse && onFinish();

    stopTimeout && stopTimeout();

    return await new Promise((resolve, reject) => {
      settle(resolve, reject, {
        data: responseData,
        headers: AxiosHeaders.from(response.headers),
        status: response.status,
        statusText: response.statusText,
        config,
        request
      });
    })
  } catch (err) {
    onFinish();

    if (err && err.name === 'TypeError' && /fetch/i.test(err.message)) {
      throw Object.assign(
        new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request),
        {
          cause: err.cause || err
        }
      )
    }

    throw AxiosError.from(err, err && err.code, config, request);
  }
});

const knownAdapters = {
  http: httpAdapter,
  xhr: xhrAdapter,
  fetch: fetchAdapter
};

utils$1.forEach(knownAdapters, (fn, value) => {
  if (fn) {
    try {
      Object.defineProperty(fn, 'name', {value});
    } catch (e) {
      // eslint-disable-next-line no-empty
    }
    Object.defineProperty(fn, 'adapterName', {value});
  }
});

const renderReason = (reason) => `- ${reason}`;

const isResolvedHandle = (adapter) => utils$1.isFunction(adapter) || adapter === null || adapter === false;

var adapters = {
  getAdapter: (adapters) => {
    adapters = utils$1.isArray(adapters) ? adapters : [adapters];

    const {length} = adapters;
    let nameOrAdapter;
    let adapter;

    const rejectedReasons = {};

    for (let i = 0; i < length; i++) {
      nameOrAdapter = adapters[i];
      let id;

      adapter = nameOrAdapter;

      if (!isResolvedHandle(nameOrAdapter)) {
        adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];

        if (adapter === undefined) {
          throw new AxiosError(`Unknown adapter '${id}'`);
        }
      }

      if (adapter) {
        break;
      }

      rejectedReasons[id || '#' + i] = adapter;
    }

    if (!adapter) {

      const reasons = Object.entries(rejectedReasons)
        .map(([id, state]) => `adapter ${id} ` +
          (state === false ? 'is not supported by the environment' : 'is not available in the build')
        );

      let s = length ?
        (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
        'as no adapter specified';

      throw new AxiosError(
        `There is no suitable adapter to dispatch the request ` + s,
        'ERR_NOT_SUPPORT'
      );
    }

    return adapter;
  },
  adapters: knownAdapters
};

/**
 * Throws a `CanceledError` if cancellation has been requested.
 *
 * @param {Object} config The config that is to be used for the request
 *
 * @returns {void}
 */
function throwIfCancellationRequested(config) {
  if (config.cancelToken) {
    config.cancelToken.throwIfRequested();
  }

  if (config.signal && config.signal.aborted) {
    throw new CanceledError(null, config);
  }
}

/**
 * Dispatch a request to the server using the configured adapter.
 *
 * @param {object} config The config that is to be used for the request
 *
 * @returns {Promise} The Promise to be fulfilled
 */
function dispatchRequest(config) {
  throwIfCancellationRequested(config);

  config.headers = AxiosHeaders.from(config.headers);

  // Transform request data
  config.data = transformData.call(
    config,
    config.transformRequest
  );

  if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
    config.headers.setContentType('application/x-www-form-urlencoded', false);
  }

  const adapter = adapters.getAdapter(config.adapter || defaults.adapter);

  return adapter(config).then(function onAdapterResolution(response) {
    throwIfCancellationRequested(config);

    // Transform response data
    response.data = transformData.call(
      config,
      config.transformResponse,
      response
    );

    response.headers = AxiosHeaders.from(response.headers);

    return response;
  }, function onAdapterRejection(reason) {
    if (!isCancel(reason)) {
      throwIfCancellationRequested(config);

      // Transform response data
      if (reason && reason.response) {
        reason.response.data = transformData.call(
          config,
          config.transformResponse,
          reason.response
        );
        reason.response.headers = AxiosHeaders.from(reason.response.headers);
      }
    }

    return Promise.reject(reason);
  });
}

const VERSION = "1.7.2";

const validators$1 = {};

// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
  validators$1[type] = function validator(thing) {
    return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  };
});

const deprecatedWarnings = {};

/**
 * Transitional option validator
 *
 * @param {function|boolean?} validator - set to false if the transitional option has been removed
 * @param {string?} version - deprecated version / removed since version
 * @param {string?} message - some message with additional info
 *
 * @returns {function}
 */
validators$1.transitional = function transitional(validator, version, message) {
  function formatMessage(opt, desc) {
    return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
  }

  // eslint-disable-next-line func-names
  return (value, opt, opts) => {
    if (validator === false) {
      throw new AxiosError(
        formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
        AxiosError.ERR_DEPRECATED
      );
    }

    if (version && !deprecatedWarnings[opt]) {
      deprecatedWarnings[opt] = true;
      // eslint-disable-next-line no-console
      console.warn(
        formatMessage(
          opt,
          ' has been deprecated since v' + version + ' and will be removed in the near future'
        )
      );
    }

    return validator ? validator(value, opt, opts) : true;
  };
};

/**
 * Assert object's properties type
 *
 * @param {object} options
 * @param {object} schema
 * @param {boolean?} allowUnknown
 *
 * @returns {object}
 */

function assertOptions(options, schema, allowUnknown) {
  if (typeof options !== 'object') {
    throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
  }
  const keys = Object.keys(options);
  let i = keys.length;
  while (i-- > 0) {
    const opt = keys[i];
    const validator = schema[opt];
    if (validator) {
      const value = options[opt];
      const result = value === undefined || validator(value, opt, options);
      if (result !== true) {
        throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
      }
      continue;
    }
    if (allowUnknown !== true) {
      throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
    }
  }
}

var validator = {
  assertOptions,
  validators: validators$1
};

const validators = validator.validators;

/**
 * Create a new instance of Axios
 *
 * @param {Object} instanceConfig The default config for the instance
 *
 * @return {Axios} A new instance of Axios
 */
class Axios {
  constructor(instanceConfig) {
    this.defaults = instanceConfig;
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
  }

  /**
   * Dispatch a request
   *
   * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
   * @param {?Object} config
   *
   * @returns {Promise} The Promise to be fulfilled
   */
  async request(configOrUrl, config) {
    try {
      return await this._request(configOrUrl, config);
    } catch (err) {
      if (err instanceof Error) {
        let dummy;

        Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());

        // slice off the Error: ... line
        const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
        try {
          if (!err.stack) {
            err.stack = stack;
            // match without the 2 top stack lines
          } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
            err.stack += '\n' + stack;
          }
        } catch (e) {
          // ignore the case where "stack" is an un-writable property
        }
      }

      throw err;
    }
  }

  _request(configOrUrl, config) {
    /*eslint no-param-reassign:0*/
    // Allow for axios('example/url'[, config]) a la fetch API
    if (typeof configOrUrl === 'string') {
      config = config || {};
      config.url = configOrUrl;
    } else {
      config = configOrUrl || {};
    }

    config = mergeConfig(this.defaults, config);

    const {transitional, paramsSerializer, headers} = config;

    if (transitional !== undefined) {
      validator.assertOptions(transitional, {
        silentJSONParsing: validators.transitional(validators.boolean),
        forcedJSONParsing: validators.transitional(validators.boolean),
        clarifyTimeoutError: validators.transitional(validators.boolean)
      }, false);
    }

    if (paramsSerializer != null) {
      if (utils$1.isFunction(paramsSerializer)) {
        config.paramsSerializer = {
          serialize: paramsSerializer
        };
      } else {
        validator.assertOptions(paramsSerializer, {
          encode: validators.function,
          serialize: validators.function
        }, true);
      }
    }

    // Set config.method
    config.method = (config.method || this.defaults.method || 'get').toLowerCase();

    // Flatten headers
    let contextHeaders = headers && utils$1.merge(
      headers.common,
      headers[config.method]
    );

    headers && utils$1.forEach(
      ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
      (method) => {
        delete headers[method];
      }
    );

    config.headers = AxiosHeaders.concat(contextHeaders, headers);

    // filter out skipped interceptors
    const requestInterceptorChain = [];
    let synchronousRequestInterceptors = true;
    this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
      if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
        return;
      }

      synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;

      requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
    });

    const responseInterceptorChain = [];
    this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
      responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
    });

    let promise;
    let i = 0;
    let len;

    if (!synchronousRequestInterceptors) {
      const chain = [dispatchRequest.bind(this), undefined];
      chain.unshift.apply(chain, requestInterceptorChain);
      chain.push.apply(chain, responseInterceptorChain);
      len = chain.length;

      promise = Promise.resolve(config);

      while (i < len) {
        promise = promise.then(chain[i++], chain[i++]);
      }

      return promise;
    }

    len = requestInterceptorChain.length;

    let newConfig = config;

    i = 0;

    while (i < len) {
      const onFulfilled = requestInterceptorChain[i++];
      const onRejected = requestInterceptorChain[i++];
      try {
        newConfig = onFulfilled(newConfig);
      } catch (error) {
        onRejected.call(this, error);
        break;
      }
    }

    try {
      promise = dispatchRequest.call(this, newConfig);
    } catch (error) {
      return Promise.reject(error);
    }

    i = 0;
    len = responseInterceptorChain.length;

    while (i < len) {
      promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
    }

    return promise;
  }

  getUri(config) {
    config = mergeConfig(this.defaults, config);
    const fullPath = buildFullPath(config.baseURL, config.url);
    return buildURL(fullPath, config.params, config.paramsSerializer);
  }
}

// Provide aliases for supported request methods
utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  /*eslint func-names:0*/
  Axios.prototype[method] = function(url, config) {
    return this.request(mergeConfig(config || {}, {
      method,
      url,
      data: (config || {}).data
    }));
  };
});

utils$1.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  /*eslint func-names:0*/

  function generateHTTPMethod(isForm) {
    return function httpMethod(url, data, config) {
      return this.request(mergeConfig(config || {}, {
        method,
        headers: isForm ? {
          'Content-Type': 'multipart/form-data'
        } : {},
        url,
        data
      }));
    };
  }

  Axios.prototype[method] = generateHTTPMethod();

  Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
});

/**
 * A `CancelToken` is an object that can be used to request cancellation of an operation.
 *
 * @param {Function} executor The executor function.
 *
 * @returns {CancelToken}
 */
class CancelToken {
  constructor(executor) {
    if (typeof executor !== 'function') {
      throw new TypeError('executor must be a function.');
    }

    let resolvePromise;

    this.promise = new Promise(function promiseExecutor(resolve) {
      resolvePromise = resolve;
    });

    const token = this;

    // eslint-disable-next-line func-names
    this.promise.then(cancel => {
      if (!token._listeners) return;

      let i = token._listeners.length;

      while (i-- > 0) {
        token._listeners[i](cancel);
      }
      token._listeners = null;
    });

    // eslint-disable-next-line func-names
    this.promise.then = onfulfilled => {
      let _resolve;
      // eslint-disable-next-line func-names
      const promise = new Promise(resolve => {
        token.subscribe(resolve);
        _resolve = resolve;
      }).then(onfulfilled);

      promise.cancel = function reject() {
        token.unsubscribe(_resolve);
      };

      return promise;
    };

    executor(function cancel(message, config, request) {
      if (token.reason) {
        // Cancellation has already been requested
        return;
      }

      token.reason = new CanceledError(message, config, request);
      resolvePromise(token.reason);
    });
  }

  /**
   * Throws a `CanceledError` if cancellation has been requested.
   */
  throwIfRequested() {
    if (this.reason) {
      throw this.reason;
    }
  }

  /**
   * Subscribe to the cancel signal
   */

  subscribe(listener) {
    if (this.reason) {
      listener(this.reason);
      return;
    }

    if (this._listeners) {
      this._listeners.push(listener);
    } else {
      this._listeners = [listener];
    }
  }

  /**
   * Unsubscribe from the cancel signal
   */

  unsubscribe(listener) {
    if (!this._listeners) {
      return;
    }
    const index = this._listeners.indexOf(listener);
    if (index !== -1) {
      this._listeners.splice(index, 1);
    }
  }

  /**
   * Returns an object that contains a new `CancelToken` and a function that, when called,
   * cancels the `CancelToken`.
   */
  static source() {
    let cancel;
    const token = new CancelToken(function executor(c) {
      cancel = c;
    });
    return {
      token,
      cancel
    };
  }
}

/**
 * Syntactic sugar for invoking a function and expanding an array for arguments.
 *
 * Common use case would be to use `Function.prototype.apply`.
 *
 *  ```js
 *  function f(x, y, z) {}
 *  var args = [1, 2, 3];
 *  f.apply(null, args);
 *  ```
 *
 * With `spread` this example can be re-written.
 *
 *  ```js
 *  spread(function(x, y, z) {})([1, 2, 3]);
 *  ```
 *
 * @param {Function} callback
 *
 * @returns {Function}
 */
function spread(callback) {
  return function wrap(arr) {
    return callback.apply(null, arr);
  };
}

/**
 * Determines whether the payload is an error thrown by Axios
 *
 * @param {*} payload The value to test
 *
 * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
 */
function isAxiosError(payload) {
  return utils$1.isObject(payload) && (payload.isAxiosError === true);
}

const HttpStatusCode = {
  Continue: 100,
  SwitchingProtocols: 101,
  Processing: 102,
  EarlyHints: 103,
  Ok: 200,
  Created: 201,
  Accepted: 202,
  NonAuthoritativeInformation: 203,
  NoContent: 204,
  ResetContent: 205,
  PartialContent: 206,
  MultiStatus: 207,
  AlreadyReported: 208,
  ImUsed: 226,
  MultipleChoices: 300,
  MovedPermanently: 301,
  Found: 302,
  SeeOther: 303,
  NotModified: 304,
  UseProxy: 305,
  Unused: 306,
  TemporaryRedirect: 307,
  PermanentRedirect: 308,
  BadRequest: 400,
  Unauthorized: 401,
  PaymentRequired: 402,
  Forbidden: 403,
  NotFound: 404,
  MethodNotAllowed: 405,
  NotAcceptable: 406,
  ProxyAuthenticationRequired: 407,
  RequestTimeout: 408,
  Conflict: 409,
  Gone: 410,
  LengthRequired: 411,
  PreconditionFailed: 412,
  PayloadTooLarge: 413,
  UriTooLong: 414,
  UnsupportedMediaType: 415,
  RangeNotSatisfiable: 416,
  ExpectationFailed: 417,
  ImATeapot: 418,
  MisdirectedRequest: 421,
  UnprocessableEntity: 422,
  Locked: 423,
  FailedDependency: 424,
  TooEarly: 425,
  UpgradeRequired: 426,
  PreconditionRequired: 428,
  TooManyRequests: 429,
  RequestHeaderFieldsTooLarge: 431,
  UnavailableForLegalReasons: 451,
  InternalServerError: 500,
  NotImplemented: 501,
  BadGateway: 502,
  ServiceUnavailable: 503,
  GatewayTimeout: 504,
  HttpVersionNotSupported: 505,
  VariantAlsoNegotiates: 506,
  InsufficientStorage: 507,
  LoopDetected: 508,
  NotExtended: 510,
  NetworkAuthenticationRequired: 511,
};

Object.entries(HttpStatusCode).forEach(([key, value]) => {
  HttpStatusCode[value] = key;
});

/**
 * Create an instance of Axios
 *
 * @param {Object} defaultConfig The default config for the instance
 *
 * @returns {Axios} A new instance of Axios
 */
function createInstance(defaultConfig) {
  const context = new Axios(defaultConfig);
  const instance = bind(Axios.prototype.request, context);

  // Copy axios.prototype to instance
  utils$1.extend(instance, Axios.prototype, context, {allOwnKeys: true});

  // Copy context to instance
  utils$1.extend(instance, context, null, {allOwnKeys: true});

  // Factory for creating new instances
  instance.create = function create(instanceConfig) {
    return createInstance(mergeConfig(defaultConfig, instanceConfig));
  };

  return instance;
}

// Create the default instance to be exported
const axios = createInstance(defaults);

// Expose Axios class to allow class inheritance
axios.Axios = Axios;

// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;

// Expose AxiosError class
axios.AxiosError = AxiosError;

// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;

// Expose all/spread
axios.all = function all(promises) {
  return Promise.all(promises);
};

axios.spread = spread;

// Expose isAxiosError
axios.isAxiosError = isAxiosError;

// Expose mergeConfig
axios.mergeConfig = mergeConfig;

axios.AxiosHeaders = AxiosHeaders;

axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);

axios.getAdapter = adapters.getAdapter;

axios.HttpStatusCode = HttpStatusCode;

axios.default = axios;

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

function _defineProperties(target, props) {
  for (var i = 0; i < props.length; i++) {
    var descriptor = props[i];
    descriptor.enumerable = descriptor.enumerable || false;
    descriptor.configurable = true;
    if ("value" in descriptor) descriptor.writable = true;
    Object.defineProperty(target, descriptor.key, descriptor);
  }
}

function _createClass(Constructor, protoProps, staticProps) {
  if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  if (staticProps) _defineProperties(Constructor, staticProps);
  return Constructor;
}

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }

  return obj;
}

function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var Client = /*#__PURE__*/function () {
  function Client(common, serverMap, apiMap) {
    _classCallCheck(this, Client);

    _defineProperty(this, "common", void 0);

    _defineProperty(this, "base", void 0);

    _defineProperty(this, "serverMap", void 0);

    _defineProperty(this, "apiMap", void 0);

    _defineProperty(this, "apis", void 0);

    _defineProperty(this, "instance", void 0);

    this.common = common || {};
    this.instance = axios.create(common);
    this.serverMap = serverMap || {};
    this.apiMap = apiMap || {};
    this.apis = {};

    if (Object.keys(this.serverMap).length && Object.keys(this.apiMap).length) {
      this.base = this.getDefault();
      this.formatConfigUrl();
      this.combine2Request();
    }

    this.middleware();
  }
  /**
   * 获取默认的配置
   * @returns
   */


  _createClass(Client, [{
    key: "getDefault",
    value: function getDefault() {
      var base = '';

      for (var _i = 0, _Object$keys = Object.keys(this.serverMap); _i < _Object$keys.length; _i++) {
        var key = _Object$keys[_i];

        if (this.serverMap[key]["default"]) {
          base = key;
        }
      }

      if (!base) {
        console.error('apis: 找不到默认服务器配置');
      }

      return base;
    }
    /**
     * 配置正确的baseURL,如果没有baseURL就读默认的
     *  @returns
     */

  }, {
    key: "formatConfigUrl",
    value: function formatConfigUrl() {
      for (var _i2 = 0, _Object$keys2 = Object.keys(this.apiMap); _i2 < _Object$keys2.length; _i2++) {
        var key = _Object$keys2[_i2];
        var item = this.apiMap[key];

        if (!item.server) {
          item.server = this.base;
        }

        this.apiMap[key] = _objectSpread$1(_objectSpread$1({}, this.serverMap[item.server]), item);
      }
    }
  }, {
    key: "get",
    value: function get(url, request) {
      request = _objectSpread$1(_objectSpread$1({}, request), {}, {
        method: 'GET'
      });
      return this.request(url, request);
    }
  }, {
    key: "delete",
    value: function _delete(url, request) {
      request = _objectSpread$1(_objectSpread$1({}, request), {}, {
        method: 'DELETE'
      });
      return this.request(url, request);
    }
  }, {
    key: "post",
    value: function post(url, request) {
      request = _objectSpread$1(_objectSpread$1({}, request), {}, {
        method: 'POST'
      });
      return this.request(url, request);
    }
  }, {
    key: "put",
    value: function put(url, request) {
      request = _objectSpread$1(_objectSpread$1({}, request), {}, {
        method: 'PUT'
      });
      return this.request(url, request);
    }
  }, {
    key: "patch",
    value: function patch(url, request) {
      request = _objectSpread$1(_objectSpread$1({}, request), {}, {
        method: 'PATCH'
      });
      return this.request(url, request);
    }
  }, {
    key: "request",
    value: function request(url, _request) {
      var rest = _request.rest || {};
      var path = url;

      if (Object.keys(rest).length) {
        path = this.restful(url, rest);
      } // 合并公共配置


      var options = _objectSpread$1(_objectSpread$1({}, this.common), _request);

      return this.instance.request(_objectSpread$1(_objectSpread$1({}, options), {}, {
        url: path
      }));
    }
    /**
     * 将url转换为restful风格
     * @param url
     * @param rest
     * @returns
     */

  }, {
    key: "restful",
    value: function restful(url, rest) {
      var regex = /:[^/]*/g;
      return url.replace(regex, function (p) {
        var key = p.slice(1);

        if (rest[key]) {
          return rest[key];
        }

        return p;
      });
    }
    /**
     * 将restful config配置合并
     * @param config1 apis文件的基本配置信息
     * @param config2 用户传入的配置信息
     * @returns
     */

  }, {
    key: "rest2Combine",
    value: function rest2Combine(config1, config2) {
      var reConf = _objectSpread$1({}, config2);

      if (config2.rest) {
        reConf.url = this.restful(config1.url, config2.rest);
      }

      return _objectSpread$1(_objectSpread$1({}, config1), reConf);
    }
    /**
     * 合并配置,转化为请求方法
     * @returns
     */

  }, {
    key: "combine2Request",
    value: function combine2Request() {
      var _this = this;

      var _loop = function _loop() {
        var key = _Object$keys3[_i3];

        _this.apis[key] = function (config) {
          var result = _this.apiMap[key];

          if (config) {
            result = _this.rest2Combine(_this.apiMap[key], config);
          }

          return _this.instance.request(result);
        };
      };

      for (var _i3 = 0, _Object$keys3 = Object.keys(this.apiMap); _i3 < _Object$keys3.length; _i3++) {
        _loop();
      }
    }
    /**
     * client拦截器处理
     */

  }, {
    key: "middleware",
    value: function middleware() {
      var _this2 = this;

      Client.reqMiddleware.map(function (middleware) {
        return _this2.instance.interceptors.request.use(middleware.onFulfilled, middleware.onRejected);
      });
      Client.resMiddleware.map(function (middleware) {
        return _this2.instance.interceptors.response.use(middleware.onFulfilled, middleware.onRejected);
      });
    }
  }], [{
    key: "useReq",
    value: function useReq(onFulfilled, onRejected) {
      Client.reqMiddleware.push({
        onFulfilled: onFulfilled,
        onRejected: onRejected
      });
    }
  }, {
    key: "useRes",
    value: function useRes(onFulfilled, onRejected) {
      Client.resMiddleware.push({
        onFulfilled: onFulfilled,
        onRejected: onRejected
      });
    }
  }, {
    key: "create",
    value: function create(common, serverMap, apiMap) {
      var client = new Client(common, serverMap, apiMap);
      return client;
    }
  }]);

  return Client;
}();

_defineProperty(Client, "reqMiddleware", []);

_defineProperty(Client, "resMiddleware", []);

var apiMap = {
  guildURI: '/guilds/:guildID',
  guildMembersURI: '/guilds/:guildID/members',
  guildMemberURI: '/guilds/:guildID/members/:userID',
  channelsURI: '/guilds/:guildID/channels',
  channelURI: '/channels/:channelID',
  guildAnnouncesURI: '/guilds/:guildID/announces',
  guildAnnounceURI: '/guilds/:guildID/announces/:messageID',
  channelAnnouncesURI: '/channels/:channelID/announces',
  channelAnnounceURI: '/channels/:channelID/announces/:messageID',
  messagesURI: '/channels/:channelID/messages',
  messageURI: '/channels/:channelID/messages/:messageID',
  userMeURI: '/users/@me',
  userMeGuildsURI: '/users/@me/guilds',
  muteURI: '/guilds/:guildID/mute',
  muteMemberURI: '/guilds/:guildID/members/:userID/mute',
  muteMembersURI: '/guilds/:guildID/mute',
  gatewayURI: '/gateway',
  gatewayBotURI: '/gateway/bot',
  audioControlURI: '/channels/:channelID/audio',
  rolesURI: '/guilds/:guildID/roles',
  roleURI: '/guilds/:guildID/roles/:roleID',
  memberRoleURI: '/guilds/:guildID/members/:userID/roles/:roleID',
  userMeDMURI: '/users/@me/dms',
  dmsURI: '/dms/:guildID/messages',
  channelPermissionsURI: '/channels/:channelID/members/:userID/permissions',
  channelRolePermissionsURI: '/channels/:channelID/roles/:roleID/permissions',
  schedulesURI: '/channels/:channelID/schedules',
  scheduleURI: '/channels/:channelID/schedules/:scheduleID',
  guildPermissionURI: '/guilds/:guildID/api_permission',
  guildPermissionDemandURI: '/guilds/:guildID/api_permission/demand',
  wsInfo: '/gateway/bot',
  reactionURI: '/channels/:channelID/messages/:messageID/reactions/:emojiType/:emojiID',
  pinsMessageIdURI: '/channels/:channelID/pins/:messageID',
  pinsMessageURI: '/channels/:channelID/pins',
  interactionURI: '/interactions/:interactionID',
  guildVoiceMembersURI: '/channels/:channelID/voice/members',
  // 语音子频道在线成员车查询
  botMic: '/channels/:channelID/mic',
  // 机器人上麦|下麦

  threadsURI: '/channels/:channelID/threads'
};
var getURL = function getURL(endpoint) {
  return apiMap[endpoint];
};

var PinsMessage = /*#__PURE__*/function () {
  function PinsMessage(request, config) {
    _classCallCheck$1(this, PinsMessage);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }

  // 获取精华消息
  return _createClass$1(PinsMessage, [{
    key: "pinsMessage",
    value: function pinsMessage(channelID) {
      var options = {
        method: 'GET',
        url: getURL('pinsMessageURI'),
        rest: {
          channelID: channelID
        }
      };
      return this.request(options);
    }

    // 发送精华消息
  }, {
    key: "putPinsMessage",
    value: function putPinsMessage(channelID, messageID) {
      var options = {
        method: 'PUT',
        url: getURL('pinsMessageIdURI'),
        headers: {
          'Content-Type': 'application/json;'
        },
        rest: {
          channelID: channelID,
          messageID: messageID
        }
      };
      return this.request(options);
    }

    // 删除精华消息
  }, {
    key: "deletePinsMessage",
    value: function deletePinsMessage(channelID, messageID) {
      var options = {
        method: 'DELETE',
        url: getURL('pinsMessageIdURI'),
        rest: {
          channelID: channelID,
          messageID: messageID
        }
      };
      return this.request(options);
    }
  }]);
}();

var Reaction = /*#__PURE__*/function () {
  function Reaction(request, config) {
    _classCallCheck$1(this, Reaction);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }

  // 发表表情表态
  return _createClass$1(Reaction, [{
    key: "postReaction",
    value: function postReaction(channelId, reactionToCreate) {
      var options = {
        method: 'PUT',
        url: getURL('reactionURI'),
        rest: {
          channelID: channelId,
          messageID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.message_id,
          emojiType: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_type,
          emojiID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_id
        }
      };
      return this.request(options);
    }

    // 删除表情表态
  }, {
    key: "deleteReaction",
    value: function deleteReaction(channelId, reactionToDelete) {
      var options = {
        method: 'DELETE',
        url: getURL('reactionURI'),
        rest: {
          channelID: channelId,
          messageID: reactionToDelete === null || reactionToDelete === void 0 ? void 0 : reactionToDelete.message_id,
          emojiType: reactionToDelete === null || reactionToDelete === void 0 ? void 0 : reactionToDelete.emoji_type,
          emojiID: reactionToDelete === null || reactionToDelete === void 0 ? void 0 : reactionToDelete.emoji_id
        }
      };
      return this.request(options);
    }

    // 拉取表情表态用户列表
  }, {
    key: "getReactionUserList",
    value: function getReactionUserList(channelId, reactionToCreate, options) {
      if (!options) {
        return Promise.reject(new Error("'options' required!"));
      }
      var reqOptions = {
        method: 'GET',
        url: getURL('reactionURI'),
        rest: {
          channelID: channelId,
          messageID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.message_id,
          emojiType: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_type,
          emojiID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_id
        },
        params: options
      };
      return this.request(reqOptions);
    }
  }]);
}();

var Guild = /*#__PURE__*/function () {
  function Guild(request, config) {
    _classCallCheck$1(this, Guild);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }
  // 获取频道信息
  return _createClass$1(Guild, [{
    key: "guild",
    value: function guild(guildID) {
      var options = {
        method: 'GET',
        url: getURL('guildURI'),
        rest: {
          guildID: guildID
        }
      };
      console.log("logger", options);
      return this.request(options);
    }
    // 获取某个成员信息
  }, {
    key: "guildMember",
    value: function guildMember(guildID, userID) {
      var options = {
        method: 'GET',
        url: getURL('guildMemberURI'),
        rest: {
          guildID: guildID,
          userID: userID
        }
      };
      return this.request(options);
    }
    // 获取频道成员列表
  }, {
    key: "guildMembers",
    value: function guildMembers(guildID, pager) {
      pager = pager || {
        after: '0',
        limit: 1
      };
      var options = {
        method: 'GET',
        url: getURL('guildMembersURI'),
        rest: {
          guildID: guildID
        },
        params: pager
      };
      return this.request(options);
    }
    // 删除指定频道成员
  }, {
    key: "deleteGuildMember",
    value: function deleteGuildMember(guildID, userID) {
      var options = {
        method: 'DELETE',
        url: getURL('guildMemberURI'),
        rest: {
          guildID: guildID,
          userID: userID
        }
      };
      return this.request(options);
    }
    // 语音子频道在线成员列表
  }, {
    key: "guildVoiceMembers",
    value: function guildVoiceMembers(channelID) {
      var options = {
        method: 'GET',
        url: getURL('guildVoiceMembersURI'),
        rest: {
          channelID: channelID
        }
      };
      return this.request(options);
    }
  }]);
}();

var version = "0.1.0";

var loglevel = {exports: {}};

/*
* loglevel - https://github.com/pimterry/loglevel
*
* Copyright (c) 2013 Tim Perry
* Licensed under the MIT license.
*/

(function (module) {
	(function (root, definition) {
	    if (module.exports) {
	        module.exports = definition();
	    } else {
	        root.log = definition();
	    }
	}(commonjsGlobal, function () {

	    // Slightly dubious tricks to cut down minimized file size
	    var noop = function() {};
	    var undefinedType = "undefined";
	    var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (
	        /Trident\/|MSIE /.test(window.navigator.userAgent)
	    );

	    var logMethods = [
	        "trace",
	        "debug",
	        "info",
	        "warn",
	        "error"
	    ];

	    var _loggersByName = {};
	    var defaultLogger = null;

	    // Cross-browser bind equivalent that works at least back to IE6
	    function bindMethod(obj, methodName) {
	        var method = obj[methodName];
	        if (typeof method.bind === 'function') {
	            return method.bind(obj);
	        } else {
	            try {
	                return Function.prototype.bind.call(method, obj);
	            } catch (e) {
	                // Missing bind shim or IE8 + Modernizr, fallback to wrapping
	                return function() {
	                    return Function.prototype.apply.apply(method, [obj, arguments]);
	                };
	            }
	        }
	    }

	    // Trace() doesn't print the message in IE, so for that case we need to wrap it
	    function traceForIE() {
	        if (console.log) {
	            if (console.log.apply) {
	                console.log.apply(console, arguments);
	            } else {
	                // In old IE, native console methods themselves don't have apply().
	                Function.prototype.apply.apply(console.log, [console, arguments]);
	            }
	        }
	        if (console.trace) console.trace();
	    }

	    // Build the best logging method possible for this env
	    // Wherever possible we want to bind, not wrap, to preserve stack traces
	    function realMethod(methodName) {
	        if (methodName === 'debug') {
	            methodName = 'log';
	        }

	        if (typeof console === undefinedType) {
	            return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
	        } else if (methodName === 'trace' && isIE) {
	            return traceForIE;
	        } else if (console[methodName] !== undefined) {
	            return bindMethod(console, methodName);
	        } else if (console.log !== undefined) {
	            return bindMethod(console, 'log');
	        } else {
	            return noop;
	        }
	    }

	    // These private functions always need `this` to be set properly

	    function replaceLoggingMethods() {
	        /*jshint validthis:true */
	        var level = this.getLevel();

	        // Replace the actual methods.
	        for (var i = 0; i < logMethods.length; i++) {
	            var methodName = logMethods[i];
	            this[methodName] = (i < level) ?
	                noop :
	                this.methodFactory(methodName, level, this.name);
	        }

	        // Define log.log as an alias for log.debug
	        this.log = this.debug;

	        // Return any important warnings.
	        if (typeof console === undefinedType && level < this.levels.SILENT) {
	            return "No console available for logging";
	        }
	    }

	    // In old IE versions, the console isn't present until you first open it.
	    // We build realMethod() replacements here that regenerate logging methods
	    function enableLoggingWhenConsoleArrives(methodName) {
	        return function () {
	            if (typeof console !== undefinedType) {
	                replaceLoggingMethods.call(this);
	                this[methodName].apply(this, arguments);
	            }
	        };
	    }

	    // By default, we use closely bound real methods wherever possible, and
	    // otherwise we wait for a console to appear, and then try again.
	    function defaultMethodFactory(methodName, _level, _loggerName) {
	        /*jshint validthis:true */
	        return realMethod(methodName) ||
	               enableLoggingWhenConsoleArrives.apply(this, arguments);
	    }

	    function Logger(name, factory) {
	      // Private instance variables.
	      var self = this;
	      /**
	       * The level inherited from a parent logger (or a global default). We
	       * cache this here rather than delegating to the parent so that it stays
	       * in sync with the actual logging methods that we have installed (the
	       * parent could change levels but we might not have rebuilt the loggers
	       * in this child yet).
	       * @type {number}
	       */
	      var inheritedLevel;
	      /**
	       * The default level for this logger, if any. If set, this overrides
	       * `inheritedLevel`.
	       * @type {number|null}
	       */
	      var defaultLevel;
	      /**
	       * A user-specific level for this logger. If set, this overrides
	       * `defaultLevel`.
	       * @type {number|null}
	       */
	      var userLevel;

	      var storageKey = "loglevel";
	      if (typeof name === "string") {
	        storageKey += ":" + name;
	      } else if (typeof name === "symbol") {
	        storageKey = undefined;
	      }

	      function persistLevelIfPossible(levelNum) {
	          var levelName = (logMethods[levelNum] || 'silent').toUpperCase();

	          if (typeof window === undefinedType || !storageKey) return;

	          // Use localStorage if available
	          try {
	              window.localStorage[storageKey] = levelName;
	              return;
	          } catch (ignore) {}

	          // Use session cookie as fallback
	          try {
	              window.document.cookie =
	                encodeURIComponent(storageKey) + "=" + levelName + ";";
	          } catch (ignore) {}
	      }

	      function getPersistedLevel() {
	          var storedLevel;

	          if (typeof window === undefinedType || !storageKey) return;

	          try {
	              storedLevel = window.localStorage[storageKey];
	          } catch (ignore) {}

	          // Fallback to cookies if local storage gives us nothing
	          if (typeof storedLevel === undefinedType) {
	              try {
	                  var cookie = window.document.cookie;
	                  var cookieName = encodeURIComponent(storageKey);
	                  var location = cookie.indexOf(cookieName + "=");
	                  if (location !== -1) {
	                      storedLevel = /^([^;]+)/.exec(
	                          cookie.slice(location + cookieName.length + 1)
	                      )[1];
	                  }
	              } catch (ignore) {}
	          }

	          // If the stored level is not valid, treat it as if nothing was stored.
	          if (self.levels[storedLevel] === undefined) {
	              storedLevel = undefined;
	          }

	          return storedLevel;
	      }

	      function clearPersistedLevel() {
	          if (typeof window === undefinedType || !storageKey) return;

	          // Use localStorage if available
	          try {
	              window.localStorage.removeItem(storageKey);
	          } catch (ignore) {}

	          // Use session cookie as fallback
	          try {
	              window.document.cookie =
	                encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
	          } catch (ignore) {}
	      }

	      function normalizeLevel(input) {
	          var level = input;
	          if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
	              level = self.levels[level.toUpperCase()];
	          }
	          if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
	              return level;
	          } else {
	              throw new TypeError("log.setLevel() called with invalid level: " + input);
	          }
	      }

	      /*
	       *
	       * Public logger API - see https://github.com/pimterry/loglevel for details
	       *
	       */

	      self.name = name;

	      self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
	          "ERROR": 4, "SILENT": 5};

	      self.methodFactory = factory || defaultMethodFactory;

	      self.getLevel = function () {
	          if (userLevel != null) {
	            return userLevel;
	          } else if (defaultLevel != null) {
	            return defaultLevel;
	          } else {
	            return inheritedLevel;
	          }
	      };

	      self.setLevel = function (level, persist) {
	          userLevel = normalizeLevel(level);
	          if (persist !== false) {  // defaults to true
	              persistLevelIfPossible(userLevel);
	          }

	          // NOTE: in v2, this should call rebuild(), which updates children.
	          return replaceLoggingMethods.call(self);
	      };

	      self.setDefaultLevel = function (level) {
	          defaultLevel = normalizeLevel(level);
	          if (!getPersistedLevel()) {
	              self.setLevel(level, false);
	          }
	      };

	      self.resetLevel = function () {
	          userLevel = null;
	          clearPersistedLevel();
	          replaceLoggingMethods.call(self);
	      };

	      self.enableAll = function(persist) {
	          self.setLevel(self.levels.TRACE, persist);
	      };

	      self.disableAll = function(persist) {
	          self.setLevel(self.levels.SILENT, persist);
	      };

	      self.rebuild = function () {
	          if (defaultLogger !== self) {
	              inheritedLevel = normalizeLevel(defaultLogger.getLevel());
	          }
	          replaceLoggingMethods.call(self);

	          if (defaultLogger === self) {
	              for (var childName in _loggersByName) {
	                _loggersByName[childName].rebuild();
	              }
	          }
	      };

	      // Initialize all the internal levels.
	      inheritedLevel = normalizeLevel(
	          defaultLogger ? defaultLogger.getLevel() : "WARN"
	      );
	      var initialLevel = getPersistedLevel();
	      if (initialLevel != null) {
	          userLevel = normalizeLevel(initialLevel);
	      }
	      replaceLoggingMethods.call(self);
	    }

	    /*
	     *
	     * Top-level API
	     *
	     */

	    defaultLogger = new Logger();

	    defaultLogger.getLogger = function getLogger(name) {
	        if ((typeof name !== "symbol" && typeof name !== "string") || name === "") {
	            throw new TypeError("You must supply a name when creating a logger.");
	        }

	        var logger = _loggersByName[name];
	        if (!logger) {
	            logger = _loggersByName[name] = new Logger(
	                name,
	                defaultLogger.methodFactory
	            );
	        }
	        return logger;
	    };

	    // Grab the current global log variable in case of overwrite
	    var _log = (typeof window !== undefinedType) ? window.log : undefined;
	    defaultLogger.noConflict = function() {
	        if (typeof window !== undefinedType &&
	               window.log === defaultLogger) {
	            window.log = _log;
	        }

	        return defaultLogger;
	    };

	    defaultLogger.getLoggers = function getLoggers() {
	        return _loggersByName;
	    };

	    // ES6 default export, for compatibility
	    defaultLogger['default'] = defaultLogger;

	    return defaultLogger;
	})); 
} (loglevel));

var loglevelExports = loglevel.exports;
var log = /*@__PURE__*/getDefaultExportFromCjs(loglevelExports);

log.setLevel('info');
log.setLevel('trace');
var BotLogger = log;

// 转为对象
var toObject = function toObject(data) {
  if (Buffer.isBuffer(data)) return JSON.parse(data.toString());
  if (_typeof(data) === 'object') return data;
  if (typeof data === 'string') return JSON.parse(data);
  // return String(data);
};

// 获取number类型的10位时间戳
var getTimeStampNumber = function getTimeStampNumber() {
  return Number(new Date().getTime().toString().substr(0, 10));
};

// 添加 User-Agent
var addUserAgent = function addUserAgent(header) {
  var sdkVersion = version;
  header['User-Agent'] = "BotNodeSDK/v".concat(sdkVersion);
};
// 添加 User-Agent
var addAuthorization = function addAuthorization(header, appID, token) {
  header['Authorization'] = "Bot ".concat(appID, ".").concat(token);
};
// 组装完整Url
var buildUrl = function buildUrl() {
  var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var isSandbox = arguments.length > 1 ? arguments[1] : undefined;
  return "".concat(isSandbox ? 'https://sandbox.api.sgroup.qq.com' : 'https://api.sgroup.qq.com').concat(path);
};

var Channel = /*#__PURE__*/function () {
  function Channel(request, config) {
    _classCallCheck$1(this, Channel);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }
  // 获取子频道信息
  return _createClass$1(Channel, [{
    key: "channel",
    value: function channel(channelID) {
      var options = {
        method: 'GET',
        url: getURL('channelURI'),
        rest: {
          channelID: channelID
        }
      };
      return this.request(options);
    }

    // 获取频道下的子频道列表
  }, {
    key: "channels",
    value: function channels(guildID) {
      var options = {
        method: 'GET',
        url: getURL('channelsURI'),
        rest: {
          guildID: guildID
        }
      };
      return this.request(options);
    }

    // 创建子频道
  }, {
    key: "postChannel",
    value: function postChannel(guildID, channel) {
      if (channel.position === 0) {
        channel.position = getTimeStampNumber();
      }
      var options = {
        method: 'POST',
        url: getURL('channelsURI'),
        rest: {
          guildID: guildID
        },
        data: channel
      };
      return this.request(options);
    }

    // 修改子频道信息
  }, {
    key: "patchChannel",
    value: function patchChannel(channelID, channel) {
      if (channel.position === 0) {
        channel.position = getTimeStampNumber();
      }
      var options = {
        method: 'PATCH',
        url: getURL('channelURI'),
        rest: {
          channelID: channelID
        },
        data: channel
      };
      return this.request(options);
    }
    // 删除指定子频道
  }, {
    key: "deleteChannel",
    value: function deleteChannel(channelID) {
      var options = {
        method: 'DELETE',
        url: getURL('channelURI'),
        rest: {
          channelID: channelID
        }
      };
      return this.request(options);
    }
  }, {
    key: "createThreads",
    value: function createThreads(channelID, threads) {
      console.log(threads);
      console.log(getURL('threadsURI'));
      var options = {
        method: 'PUT',
        url: getURL('threadsURI'),
        rest: {
          channelID: channelID
        },
        data: {
          title: threads.title,
          content: threads.content,
          format: 1
        }
      };
      return this.request(options);
    }
  }]);
}();

var Me = /*#__PURE__*/function () {
  function Me(request, config) {
    _classCallCheck$1(this, Me);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }

  // 获取当前用户信息
  return _createClass$1(Me, [{
    key: "me",
    value: function me() {
      var options = {
        method: 'GET',
        url: getURL('userMeURI')
      };
      return this.request(options);
    }

    // 获取当前用户频道列表
  }, {
    key: "meGuilds",
    value: function meGuilds(options) {
      var reqOptions = {
        method: 'GET',
        url: getURL('userMeGuildsURI'),
        params: options
      };
      return this.request(reqOptions);
    }
  }]);
}();

var Message = /*#__PURE__*/function () {
  function Message(request, config) {
    _classCallCheck$1(this, Message);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }
  // 获取指定消息
  return _createClass$1(Message, [{
    key: "message",
    value: function message(channelID, messageID) {
      var options = {
        method: 'GET',
        url: getURL('messageURI'),
        rest: {
          channelID: channelID,
          messageID: messageID
        }
      };
      return this.request(options);
    }
    // 获取消息列表
  }, {
    key: "messages",
    value: function messages(channelID, pager) {
      var params = Object.create(null);
      if (pager && pager.type && pager.id) {
        params[pager.type] = pager.id;
        params.limit = pager.limit || 20;
      }
      var options = {
        method: 'GET',
        url: getURL('messagesURI'),
        rest: {
          channelID: channelID
        },
        params: params
      };
      return this.request(options);
    }

    // 发送消息
  }, {
    key: "postMessage",
    value: function postMessage(channelID, message) {
      var options = {
        method: 'POST',
        url: getURL('messagesURI'),
        rest: {
          channelID: channelID
        },
        data: message
      };
      return this.request(options);
    }

    // 撤回消息
  }, {
    key: "deleteMessage",
    value: function deleteMessage(channelID, messageID, hideTip) {
      var params = Object.create(null);
      if (hideTip) {
        params.hidetip = hideTip;
      }
      var options = {
        method: 'DELETE',
        url: getURL('messageURI'),
        rest: {
          channelID: channelID,
          messageID: messageID
        },
        params: params
      };
      return this.request(options);
    }
  }]);
}();

var Member = /*#__PURE__*/function () {
  function Member(request, config) {
    _classCallCheck$1(this, Member);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }
  // 增加频道身份组成员
  return _createClass$1(Member, [{
    key: "memberAddRole",
    value: function memberAddRole(guildID, roleID, userID, channel // 兼容原来传递 channel 对象的逻辑，后续仅支持 string
    ) {
      var channelObj = typeof channel === 'string' ? {
        channel: {
          id: channel
        }
      } : channel;
      var options = {
        method: 'PUT',
        url: getURL('memberRoleURI'),
        rest: {
          guildID: guildID,
          userID: userID,
          roleID: roleID
        },
        data: channelObj
      };
      return this.request(options);
    }
    // 删除频道身份组成员
  }, {
    key: "memberDeleteRole",
    value: function memberDeleteRole(guildID, roleID, userID, channel // 兼容原来传递 channel 对象的逻辑，后续仅支持 string
    ) {
      var channelObj = typeof channel === 'string' ? {
        channel: {
          id: channel
        }
      } : channel;
      var options = {
        method: 'DELETE',
        url: getURL('memberRoleURI'),
        rest: {
          guildID: guildID,
          userID: userID,
          roleID: roleID
        },
        data: channelObj
      };
      return this.request(options);
    }
  }]);
}();

// 默认的filter：0 1 代表是否设置 0-否 1-是
var defaultFilter = {
  name: 1,
  color: 1,
  hoist: 1
};

// 用户组默认颜色值
var defaultColor = 4278245297;
var Role = /*#__PURE__*/function () {
  function Role(request, config) {
    _classCallCheck$1(this, Role);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }
  // 获取频道身份组列表
  return _createClass$1(Role, [{
    key: "roles",
    value: function roles(guildID) {
      var options = {
        method: 'GET',
        url: getURL('rolesURI'),
        rest: {
          guildID: guildID
        }
      };
      return this.request(options);
    }

    // 创建频道身份组
  }, {
    key: "postRole",
    value: function postRole(guildID, role) {
      var filter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultFilter;
      if (role.color === 0) {
        role.color = defaultColor;
      }
      var options = {
        method: 'POST',
        url: getURL('rolesURI'),
        rest: {
          guildID: guildID
        },
        data: {
          guild_id: guildID,
          filter: filter,
          info: role
        }
      };
      return this.request(options);
    }

    // 修改频道身份组
  }, {
    key: "patchRole",
    value: function patchRole(guildID, roleID, role) {
      var filter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : defaultFilter;
      if (role.color === 0) {
        role.color = defaultColor;
      }
      var options = {
        method: 'PATCH',
        url: getURL('roleURI'),
        rest: {
          guildID: guildID,
          roleID: roleID
        },
        data: {
          guild_id: guildID,
          filter: filter,
          info: role
        }
      };
      return this.request(options);
    }

    // 删除频道身份组
  }, {
    key: "deleteRole",
    value: function deleteRole(guildID, roleID) {
      var options = {
        method: 'DELETE',
        url: getURL('roleURI'),
        rest: {
          guildID: guildID,
          roleID: roleID
        }
      };
      return this.request(options);
    }
  }]);
}();

var DirectMessage = /*#__PURE__*/function () {
  function DirectMessage(request, config) {
    _classCallCheck$1(this, DirectMessage);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }
  // 创建私信频道
  return _createClass$1(DirectMessage, [{
    key: "createDirectMessage",
    value: function createDirectMessage(dm) {
      var options = {
        method: 'POST',
        url: getURL('userMeDMURI'),
        data: dm
      };
      return this.request(options);
    }

    // 在私信频道内发消息
  }, {
    key: "postDirectMessage",
    value: function postDirectMessage(guildID, msg) {
      var options = {
        method: 'POST',
        url: getURL('dmsURI'),
        rest: {
          guildID: guildID
        },
        data: msg
      };
      return this.request(options);
    }
  }]);
}();

var ChannelPermissions = /*#__PURE__*/function () {
  function ChannelPermissions(request, config) {
    _classCallCheck$1(this, ChannelPermissions);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }

  // 获取指定子频道的权限
  return _createClass$1(ChannelPermissions, [{
    key: "channelPermissions",
    value: function channelPermissions(channelID, userID) {
      var options = {
        method: 'GET',
        url: getURL('channelPermissionsURI'),
        rest: {
          channelID: channelID,
          userID: userID
        }
      };
      return this.request(options);
    }

    // 修改指定子频道的权限
  }, {
    key: "putChannelPermissions",
    value: function putChannelPermissions(channelID, userID, p) {
      try {
        // 校验参数
        parseInt(p.add, 10);
        parseInt(p.remove, 10);
      } catch (error) {
        return Promise.reject(new Error('invalid parameter'));
      }
      var options = {
        method: 'PUT',
        url: getURL('channelPermissionsURI'),
        rest: {
          channelID: channelID,
          userID: userID
        },
        data: p
      };
      return this.request(options);
    }

    // 获取指定子频道身份组的权限
  }, {
    key: "channelRolePermissions",
    value: function channelRolePermissions(channelID, roleID) {
      var options = {
        method: 'GET',
        url: getURL('channelRolePermissionsURI'),
        rest: {
          channelID: channelID,
          roleID: roleID
        }
      };
      return this.request(options);
    }

    // 修改指定子频道身份组的权限
  }, {
    key: "putChannelRolePermissions",
    value: function putChannelRolePermissions(channelID, roleID, p) {
      try {
        // 校验参数
        parseInt(p.add, 10);
        parseInt(p.remove, 10);
      } catch (error) {
        return Promise.reject(new Error('invalid parameter'));
      }
      var options = {
        method: 'PUT',
        url: getURL('channelRolePermissionsURI'),
        rest: {
          channelID: channelID,
          roleID: roleID
        },
        data: p
      };
      return this.request(options);
    }
  }]);
}();

var Audio = /*#__PURE__*/function () {
  function Audio(request, config) {
    _classCallCheck$1(this, Audio);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }
  // 执行音频播放，暂停等操作
  return _createClass$1(Audio, [{
    key: "postAudio",
    value: function postAudio(channelID, audioControl) {
      var options = {
        method: 'POST',
        url: getURL('audioControlURI'),
        rest: {
          channelID: channelID
        },
        data: audioControl
      };
      return this.request(options);
    }
    // 机器人上麦
  }, {
    key: "botOnMic",
    value: function botOnMic(channelID) {
      var options = {
        method: 'PUT',
        url: getURL('botMic'),
        rest: {
          channelID: channelID
        },
        data: {}
      };
      return this.request(options);
    }
    // 机器人下麦
  }, {
    key: "botOffMic",
    value: function botOffMic(channelID) {
      var options = {
        method: 'DELETE',
        url: getURL('botMic'),
        rest: {
          channelID: channelID
        },
        data: {}
      };
      return this.request(options);
    }
  }]);
}();

var Mute = /*#__PURE__*/function () {
  function Mute(request, config) {
    _classCallCheck$1(this, Mute);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }

  // 禁言某个member
  return _createClass$1(Mute, [{
    key: "muteMember",
    value: function muteMember(guildID, userID, options) {
      if (!options) {
        return Promise.reject(new Error("'options' required!"));
      }
      var reqOptions = {
        method: 'PATCH',
        url: getURL('muteMemberURI'),
        rest: {
          guildID: guildID,
          userID: userID
        },
        data: {
          mute_end_timestamp: options === null || options === void 0 ? void 0 : options.timeTo,
          mute_seconds: options === null || options === void 0 ? void 0 : options.seconds
        }
      };
      return this.request(reqOptions);
    }

    // 禁言所有人
  }, {
    key: "muteAll",
    value: function muteAll(guildID, options) {
      if (!options) {
        return Promise.reject(new Error("'options' required!"));
      }
      var reqOptions = {
        method: 'PATCH',
        url: getURL('muteURI'),
        rest: {
          guildID: guildID
        },
        data: {
          mute_end_timestamp: options === null || options === void 0 ? void 0 : options.timeTo,
          mute_seconds: options === null || options === void 0 ? void 0 : options.seconds
        }
      };
      return this.request(reqOptions);
    }

    // 禁言批量member
  }, {
    key: "muteMembers",
    value: function muteMembers(guildID, userIDList, options) {
      if (!options) {
        return Promise.reject(new Error("'options' required!"));
      }
      var reqOptions = {
        method: 'PATCH',
        url: getURL('muteMembersURI'),
        rest: {
          guildID: guildID
        },
        data: {
          mute_end_timestamp: options === null || options === void 0 ? void 0 : options.timeTo,
          mute_seconds: options === null || options === void 0 ? void 0 : options.seconds,
          user_ids: userIDList
        }
      };
      return this.request(reqOptions);
    }
  }]);
}();

var Announce = /*#__PURE__*/function () {
  function Announce(request, config) {
    _classCallCheck$1(this, Announce);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }

  // 创建guild公告
  return _createClass$1(Announce, [{
    key: "postGuildAnnounce",
    value: function postGuildAnnounce(guildID, channelID, messageID) {
      var options = {
        method: 'POST',
        url: getURL('guildAnnouncesURI'),
        rest: {
          guildID: guildID
        },
        data: {
          channel_id: channelID,
          message_id: messageID
        }
      };
      return this.request(options);
    }

    // 删除guild公告
  }, {
    key: "deleteGuildAnnounce",
    value: function deleteGuildAnnounce(guildID, messageID) {
      var options = {
        method: 'DELETE',
        url: getURL('guildAnnounceURI'),
        rest: {
          guildID: guildID,
          messageID: messageID
        }
      };
      return this.request(options);
    }

    // 创建频道公告推荐子频道
  }, {
    key: "postGuildRecommend",
    value: function postGuildRecommend(guildID, recommendObj) {
      var options = {
        method: 'POST',
        url: getURL('guildAnnouncesURI'),
        rest: {
          guildID: guildID
        },
        data: recommendObj
      };
      return this.request(options);
    }

    // 创建channel公告
  }, {
    key: "postChannelAnnounce",
    value: function postChannelAnnounce(channelID, messageID) {
      var options = {
        method: 'POST',
        url: getURL('channelAnnouncesURI'),
        rest: {
          channelID: channelID
        },
        data: {
          message_id: messageID
        }
      };
      return this.request(options);
    }

    // 删除channel公告
  }, {
    key: "deleteChannelAnnounce",
    value: function deleteChannelAnnounce(channelID, messageID) {
      var options = {
        method: 'DELETE',
        url: getURL('channelAnnounceURI'),
        rest: {
          channelID: channelID,
          messageID: messageID
        }
      };
      return this.request(options);
    }
  }]);
}();

var Schedule = /*#__PURE__*/function () {
  function Schedule(request, config) {
    _classCallCheck$1(this, Schedule);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }

  // 获取日程列表
  return _createClass$1(Schedule, [{
    key: "schedules",
    value: function schedules(channelID, since) {
      if (since && since.length !== 13) {
        return Promise.reject(new Error("Param 'since' is invalid, millisecond timestamp expected！"));
      }
      var options = {
        method: 'GET',
        url: getURL('schedulesURI'),
        rest: {
          channelID: channelID
        },
        params: {
          since: since
        }
      };
      return this.request(options);
    }

    // 获取日程
  }, {
    key: "schedule",
    value: function schedule(channelID, scheduleID) {
      var options = {
        method: 'GET',
        url: getURL('scheduleURI'),
        rest: {
          channelID: channelID,
          scheduleID: scheduleID
        }
      };
      return this.request(options);
    }

    // 创建日程
  }, {
    key: "postSchedule",
    value: function postSchedule(channelID, schedule) {
      var options = {
        method: 'POST',
        url: getURL('schedulesURI'),
        rest: {
          channelID: channelID
        },
        data: {
          schedule: schedule
        }
      };
      return this.request(options);
    }

    // 修改日程
  }, {
    key: "patchSchedule",
    value: function patchSchedule(channelID, scheduleID, schedule) {
      var options = {
        method: 'PATCH',
        url: getURL('scheduleURI'),
        rest: {
          channelID: channelID,
          scheduleID: scheduleID
        },
        data: {
          schedule: schedule
        }
      };
      return this.request(options);
    }

    // 删除日程
  }, {
    key: "deleteSchedule",
    value: function deleteSchedule(channelID, scheduleID) {
      var options = {
        method: 'DELETE',
        url: getURL('scheduleURI'),
        rest: {
          channelID: channelID,
          scheduleID: scheduleID
        }
      };
      return this.request(options);
    }
  }]);
}();

var GuildPermissions = /*#__PURE__*/function () {
  function GuildPermissions(request, config) {
    _classCallCheck$1(this, GuildPermissions);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }

  // 获取频道可用权限列表
  return _createClass$1(GuildPermissions, [{
    key: "permissions",
    value: function permissions(guildID) {
      var options = {
        method: 'GET',
        url: getURL('guildPermissionURI'),
        rest: {
          guildID: guildID
        }
      };
      return this.request(options);
    }

    // 创建频道 API 接口权限授权链接
  }, {
    key: "postPermissionDemand",
    value: function postPermissionDemand(guildID, permissionDemandObj) {
      var options = {
        method: 'POST',
        url: getURL('guildPermissionDemandURI'),
        rest: {
          guildID: guildID
        },
        data: permissionDemandObj
      };
      return this.request(options);
    }
  }]);
}();

var Interaction = /*#__PURE__*/function () {
  function Interaction(request, config) {
    _classCallCheck$1(this, Interaction);
    _defineProperty$1(this, "request", void 0);
    _defineProperty$1(this, "config", void 0);
    this.request = request;
    this.config = config;
  }

  // 异步更新交互数据
  return _createClass$1(Interaction, [{
    key: "putInteraction",
    value: function putInteraction(interactionID, interactionData) {
      var options = {
        method: 'PUT',
        url: getURL('interactionURI'),
        headers: {
          'Content-Type': 'none'
        },
        rest: {
          interactionID: interactionID
        },
        data: interactionData
      };
      return this.request(options);
    }
  }]);
}();

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty$1(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var apiVersion = 'v1';
var OpenAPI = /*#__PURE__*/function () {
  function OpenAPI(config) {
    _classCallCheck$1(this, OpenAPI);
    _defineProperty$1(this, "config", {
      appID: '',
      token: ''
    });
    _defineProperty$1(this, "guildApi", void 0);
    _defineProperty$1(this, "channelApi", void 0);
    _defineProperty$1(this, "meApi", void 0);
    _defineProperty$1(this, "messageApi", void 0);
    _defineProperty$1(this, "memberApi", void 0);
    _defineProperty$1(this, "roleApi", void 0);
    _defineProperty$1(this, "muteApi", void 0);
    _defineProperty$1(this, "announceApi", void 0);
    _defineProperty$1(this, "scheduleApi", void 0);
    _defineProperty$1(this, "directMessageApi", void 0);
    _defineProperty$1(this, "channelPermissionsApi", void 0);
    _defineProperty$1(this, "audioApi", void 0);
    _defineProperty$1(this, "reactionApi", void 0);
    _defineProperty$1(this, "interactionApi", void 0);
    _defineProperty$1(this, "pinsMessageApi", void 0);
    _defineProperty$1(this, "guildPermissionsApi", void 0);
    this.config = config;
    this.register(this);
  }
  return _createClass$1(OpenAPI, [{
    key: "register",
    value: function register(client) {
      // 注册聚合client
      client.guildApi = new Guild(this.request, this.config);
      client.channelApi = new Channel(this.request, this.config);
      client.meApi = new Me(this.request, this.config);
      client.messageApi = new Message(this.request, this.config);
      client.memberApi = new Member(this.request, this.config);
      client.roleApi = new Role(this.request, this.config);
      client.muteApi = new Mute(this.request, this.config);
      client.announceApi = new Announce(this.request, this.config);
      client.scheduleApi = new Schedule(this.request, this.config);
      client.directMessageApi = new DirectMessage(this.request, this.config);
      client.channelPermissionsApi = new ChannelPermissions(this.request, this.config);
      client.audioApi = new Audio(this.request, this.config);
      client.guildPermissionsApi = new GuildPermissions(this.request, this.config);
      client.reactionApi = new Reaction(this.request, this.config);
      client.interactionApi = new Interaction(this.request, this.config);
      client.pinsMessageApi = new PinsMessage(this.request, this.config);
    }
    // 基础rest请求
  }, {
    key: "request",
    value: function request(options) {
      var _this$config = this.config,
        appID = _this$config.appID,
        token = _this$config.token;
      options.headers = _objectSpread({}, options.headers);

      // 添加 UA
      addUserAgent(options.headers);
      // 添加鉴权信息
      addAuthorization(options.headers, appID, token);
      // 组装完整Url
      var botUrl = buildUrl(options.url, this.config.sandbox);

      // 简化错误信息，后续可考虑通过中间件形式暴露给用户自行处理
      Client.useRes(function (result) {
        return result;
      }, function (error) {
        var _error$response, _error$response2;
        var traceid = error === null || error === void 0 || (_error$response = error.response) === null || _error$response === void 0 || (_error$response = _error$response.headers) === null || _error$response === void 0 ? void 0 : _error$response['x-tps-trace-id'];
        if (error !== null && error !== void 0 && (_error$response2 = error.response) !== null && _error$response2 !== void 0 && _error$response2.data) {
          return Promise.reject(_objectSpread(_objectSpread({}, error.response.data), {}, {
            traceid: traceid
          }));
        }
        console.error("[BOT-API][返回错误信息]", error);
        if (error !== null && error !== void 0 && error.response) {
          return Promise.reject(_objectSpread(_objectSpread({}, error.response), {}, {
            traceid: traceid
          }));
        }
        return Promise.reject(error);
      });
      var client = Client.create(options);
      return client.request(botUrl, options);
    }
  }], [{
    key: "newClient",
    value: function newClient(config) {
      return new OpenAPI(config);
    }
  }]);
}();
function v1Setup() {
  register(apiVersion, OpenAPI);
}

function _assertThisInitialized(e) {
  if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  return e;
}

function _possibleConstructorReturn(t, e) {
  if (e && ("object" == _typeof(e) || "function" == typeof e)) return e;
  if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
  return _assertThisInitialized(t);
}

function _getPrototypeOf(t) {
  return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
    return t.__proto__ || Object.getPrototypeOf(t);
  }, _getPrototypeOf(t);
}

function _setPrototypeOf(t, e) {
  return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
    return t.__proto__ = e, t;
  }, _setPrototypeOf(t, e);
}

function _inherits(t, e) {
  if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
  t.prototype = Object.create(e && e.prototype, {
    constructor: {
      value: t,
      writable: !0,
      configurable: !0
    }
  }), Object.defineProperty(t, "prototype", {
    writable: !1
  }), e && _setPrototypeOf(t, e);
}

// websocket建立成功回包

// 发送心跳入参

// 事件分发类型

// 请求得到ws地址的参数

// 请求ws地址回包对象

// ws信息

// 会话记录

// 心跳参数
var OpCode = /*#__PURE__*/function (OpCode) {
  OpCode[OpCode["DISPATCH"] = 0] = "DISPATCH";
  OpCode[OpCode["HEARTBEAT"] = 1] = "HEARTBEAT";
  OpCode[OpCode["IDENTIFY"] = 2] = "IDENTIFY";
  OpCode[OpCode["RESUME"] = 6] = "RESUME";
  OpCode[OpCode["RECONNECT"] = 7] = "RECONNECT";
  OpCode[OpCode["INVALID_SESSION"] = 9] = "INVALID_SESSION";
  OpCode[OpCode["HELLO"] = 10] = "HELLO";
  OpCode[OpCode["HEARTBEAT_ACK"] = 11] = "HEARTBEAT_ACK";
  return OpCode;
}({}); // 当发送心跳成功之后，就会收到该消息

// 可使用的intents事件类型
var AvailableIntentsEventsEnum = /*#__PURE__*/function (AvailableIntentsEventsEnum) {
  AvailableIntentsEventsEnum["GUILDS"] = "GUILDS";
  AvailableIntentsEventsEnum["GUILD_MEMBERS"] = "GUILD_MEMBERS";
  AvailableIntentsEventsEnum["GUILD_MESSAGES"] = "GUILD_MESSAGES";
  AvailableIntentsEventsEnum["GUILD_MESSAGE_REACTIONS"] = "GUILD_MESSAGE_REACTIONS";
  AvailableIntentsEventsEnum["DIRECT_MESSAGE"] = "DIRECT_MESSAGE";
  AvailableIntentsEventsEnum["FORUMS_EVENT"] = "FORUMS_EVENT";
  AvailableIntentsEventsEnum["AUDIO_ACTION"] = "AUDIO_ACTION";
  AvailableIntentsEventsEnum["PUBLIC_GUILD_MESSAGES"] = "PUBLIC_GUILD_MESSAGES";
  AvailableIntentsEventsEnum["MESSAGE_AUDIT"] = "MESSAGE_AUDIT";
  AvailableIntentsEventsEnum["INTERACTION"] = "INTERACTION";
  return AvailableIntentsEventsEnum;
}({}); // OPEN_FORUMS='OPEN_FORUMS'

// OpenAPI传过来的事件类型
var WsEventType = {
  //  ======= GUILDS ======
  GUILD_CREATE: AvailableIntentsEventsEnum.GUILDS,
  // 频道创建
  GUILD_UPDATE: AvailableIntentsEventsEnum.GUILDS,
  // 频道更新
  GUILD_DELETE: AvailableIntentsEventsEnum.GUILDS,
  // 频道删除
  CHANNEL_CREATE: AvailableIntentsEventsEnum.GUILDS,
  // 子频道创建
  CHANNEL_UPDATE: AvailableIntentsEventsEnum.GUILDS,
  // 子频道更新
  CHANNEL_DELETE: AvailableIntentsEventsEnum.GUILDS,
  // 子频道删除

  //  ======= GUILD_MEMBERS ======
  GUILD_MEMBER_ADD: AvailableIntentsEventsEnum.GUILD_MEMBERS,
  // 频道成员加入
  GUILD_MEMBER_UPDATE: AvailableIntentsEventsEnum.GUILD_MEMBERS,
  // 频道成员更新
  GUILD_MEMBER_REMOVE: AvailableIntentsEventsEnum.GUILD_MEMBERS,
  // 频道成员移除

  //  ======= GUILD_MESSAGES ======
  MESSAGE_CREATE: AvailableIntentsEventsEnum.GUILD_MESSAGES,
  // 机器人收到频道消息时触发
  MESSAGE_DELETE: AvailableIntentsEventsEnum.GUILD_MESSAGES,
  // 删除（撤回）消息事件

  //  ======= GUILD_MESSAGE_REACTIONS ======
  MESSAGE_REACTION_ADD: AvailableIntentsEventsEnum.GUILD_MESSAGE_REACTIONS,
  // 为消息添加表情表态
  MESSAGE_REACTION_REMOVE: AvailableIntentsEventsEnum.GUILD_MESSAGE_REACTIONS,
  // 为消息删除表情表态

  //  ======= DIRECT_MESSAGE ======
  DIRECT_MESSAGE_CREATE: AvailableIntentsEventsEnum.DIRECT_MESSAGE,
  // 当收到用户发给机器人的私信消息时
  DIRECT_MESSAGE_DELETE: AvailableIntentsEventsEnum.DIRECT_MESSAGE,
  // 删除（撤回）消息事件

  //  ======= INTERACTION ======
  INTERACTION_CREATE: AvailableIntentsEventsEnum.INTERACTION,
  // 互动事件创建时

  //  ======= MESSAGE_AUDIT ======
  MESSAGE_AUDIT_PASS: AvailableIntentsEventsEnum.MESSAGE_AUDIT,
  // 消息审核通过
  MESSAGE_AUDIT_REJECT: AvailableIntentsEventsEnum.MESSAGE_AUDIT,
  // 消息审核不通过

  //  ======= FORUMS_EVENT ======
  FORUM_THREAD_CREATE: AvailableIntentsEventsEnum.FORUMS_EVENT,
  // 当用户创建帖子时
  FORUM_THREAD_UPDATE: AvailableIntentsEventsEnum.FORUMS_EVENT,
  // 当用户更新帖子时
  FORUM_THREAD_DELETE: AvailableIntentsEventsEnum.FORUMS_EVENT,
  // 当用户删除帖子题时
  FORUM_POST_CREATE: AvailableIntentsEventsEnum.FORUMS_EVENT,
  // 当用户创建回帖时
  FORUM_POST_DELETE: AvailableIntentsEventsEnum.FORUMS_EVENT,
  // 当用户删除回帖时
  FORUM_REPLY_CREATE: AvailableIntentsEventsEnum.FORUMS_EVENT,
  // 当用户回复评论时
  FORUM_REPLY_DELETE: AvailableIntentsEventsEnum.FORUMS_EVENT,
  // 当用户删除评论时
  FORUM_PUBLISH_AUDIT_RESULT: AvailableIntentsEventsEnum.FORUMS_EVENT,
  // 当用户发表审核通过时

  //  ======= AUDIO_ACTION ======
  AUDIO_START: AvailableIntentsEventsEnum.AUDIO_ACTION,
  // 音频开始播放
  AUDIO_FINISH: AvailableIntentsEventsEnum.AUDIO_ACTION,
  // 音频结束播放
  AUDIO_ON_MIC: AvailableIntentsEventsEnum.AUDIO_ACTION,
  // 机器人上麦
  AUDIO_OFF_MIC: AvailableIntentsEventsEnum.AUDIO_ACTION,
  // 机器人下麦

  //  ======= PUBLIC_GUILD_MESSAGES ======
  AT_MESSAGE_CREATE: AvailableIntentsEventsEnum.PUBLIC_GUILD_MESSAGES,
  // 机器人被@时触发
  PUBLIC_MESSAGE_DELETE: AvailableIntentsEventsEnum.PUBLIC_GUILD_MESSAGES // 当频道的消息被删除时
};

// websocket错误原因
var WebsocketCloseReason = [{
  code: 4001,
  reason: '无效的opcode'
}, {
  code: 4002,
  reason: '无效的payload'
}, {
  code: 4007,
  reason: 'seq错误'
}, {
  code: 4008,
  reason: '发送 payload 过快，请重新连接，并遵守连接后返回的频控信息',
  resume: true
}, {
  code: 4009,
  reason: '连接过期，请重连',
  resume: true
}, {
  code: 4010,
  reason: '无效的shard'
}, {
  code: 4011,
  reason: '连接需要处理的guild过多，请进行合理分片'
}, {
  code: 4012,
  reason: '无效的version'
}, {
  code: 4013,
  reason: '无效的intent'
}, {
  code: 4014,
  reason: 'intent无权限'
}, {
  code: 4900,
  reason: '内部错误，请重连'
}, {
  code: 4914,
  reason: '机器人已下架,只允许连接沙箱环境,请断开连接,检验当前连接环境'
}, {
  code: 4915,
  reason: '机器人已封禁,不允许连接,请断开连接,申请解封后再连接'
}];
// 用户输入的intents类型
var IntentEvents = {
  GUILDS: 1 << 0,
  GUILD_MEMBERS: 1 << 1,
  GUILD_MESSAGES: 1 << 9,
  GUILD_MESSAGE_REACTIONS: 1 << 10,
  DIRECT_MESSAGE: 1 << 12,
  // OPEN_FORUMS_EVENT:1<<18,
  INTERACTION: 1 << 26,
  MESSAGE_AUDIT: 1 << 27,
  FORUMS_EVENT: 1 << 28,
  AUDIO_ACTION: 1 << 29,
  PUBLIC_GUILD_MESSAGES: 1 << 30
};

// Session事件
var SessionEvents = {
  CLOSED: 'CLOSED',
  READY: 'READY',
  // 已经可以通信
  ERROR: 'ERROR',
  // 会话错误
  INVALID_SESSION: 'INVALID_SESSION',
  RECONNECT: 'RECONNECT',
  // 服务端通知重新连接
  DISCONNECT: 'DISCONNECT',
  // 断线
  EVENT_WS: 'EVENT_WS',
  // 内部通信
  RESUMED: 'RESUMED',
  // 重连
  DEAD: 'DEAD' // 连接已死亡，请检查网络或重启
};

// ws地址配置
var WsObjRequestOptions = function WsObjRequestOptions(sandbox) {
  return {
    method: 'GET',
    url: buildUrl(getURL('wsInfo'), sandbox),
    headers: {
      Accept: '*/*',
      'Accept-Encoding': 'utf-8',
      'Accept-Language': 'zh-CN,zh;q=0.8',
      Connection: 'keep-alive',
      'User-Agent': apiVersion,
      Authorization: ''
    }
  };
};

// 配置文件
// 后台校验暂时用不到这块，所以给一个默认值
var Properties = {
  os: 'linux',
  browser: 'my_library',
  device: 'my_library'
};

// websocket连接
var Ws = /*#__PURE__*/function () {
  function Ws(config, event, sessionRecord) {
    _classCallCheck$1(this, Ws);
    _defineProperty$1(this, "ws", void 0);
    _defineProperty$1(this, "event", void 0);
    _defineProperty$1(this, "config", void 0);
    _defineProperty$1(this, "heartbeatInterval", void 0);
    // 心跳参数，默认为心跳测试
    _defineProperty$1(this, "heartbeatParam", {
      op: OpCode.HEARTBEAT,
      d: null // 心跳唯一值
    });
    // 是否是断线重连，如果是断线重连的话，不需要走鉴权
    _defineProperty$1(this, "isReconnect", void 0);
    // 记录会话参数
    _defineProperty$1(this, "sessionRecord", {
      sessionID: '',
      seq: 0
    });
    _defineProperty$1(this, "alive", false);
    this.config = config;
    this.isReconnect = false;
    this.event = event;
    // 如果是重连，则拿到重新的会话记录，然后进入重连步骤
    if (sessionRecord) {
      this.sessionRecord.sessionID = sessionRecord.sessionID;
      this.sessionRecord.seq = sessionRecord.seq;
      this.isReconnect = true;
    }
  }

  // 创建一个websocket连接
  return _createClass$1(Ws, [{
    key: "createWebsocket",
    value: function createWebsocket(wsData) {
      // 先链接到ws
      this.connectWs(wsData);
      // 对消息进行监听
      return this.createListening();
    }

    // 创建监听
  }, {
    key: "createListening",
    value: function createListening() {
      var _this = this;
      // websocket连接已开启
      this.ws.on('open', function () {
        BotLogger.info("[CLIENT] \u5F00\u542F");
      });

      // 接受消息
      this.ws.on('message', function (data) {
        var _wsRes$d;
        // BotLogger.info(`[CLIENT] 收到消息: ${data}`);

        // 先将消息解析
        var wsRes = toObject(data);
        // 先判断websocket连接是否成功
        if ((wsRes === null || wsRes === void 0 ? void 0 : wsRes.op) === OpCode.HELLO && wsRes !== null && wsRes !== void 0 && (_wsRes$d = wsRes.d) !== null && _wsRes$d !== void 0 && _wsRes$d.heartbeat_interval) {
          var _wsRes$d2;
          // websocket连接成功，拿到心跳周期
          _this.heartbeatInterval = wsRes === null || wsRes === void 0 || (_wsRes$d2 = wsRes.d) === null || _wsRes$d2 === void 0 ? void 0 : _wsRes$d2.heartbeat_interval;
          // 非断线重连时，需要鉴权
          _this.isReconnect ? _this.reconnectWs() : _this.authWs();
          return;
        }

        // 鉴权通过
        if (wsRes.t === SessionEvents.READY) {
          BotLogger.info("[CLIENT] \u9274\u6743\u901A\u8FC7");
          var d = wsRes.d,
            s = wsRes.s;
          var session_id = d.session_id;
          // 获取当前会话参数
          if (session_id && s) {
            _this.sessionRecord.sessionID = session_id;
            _this.sessionRecord.seq = s;
            _this.heartbeatParam.d = s;
          }
          _this.event.emit(SessionEvents.READY, {
            eventType: SessionEvents.READY,
            msg: d || ''
          });
          // 第一次发送心跳
          BotLogger.info("[CLIENT] \u53D1\u9001\u7B2C\u4E00\u6B21\u5FC3\u8DF3", _this.heartbeatParam);
          _this.sendWs(_this.heartbeatParam);
          return;
        }

        // 心跳测试
        if (wsRes.op === OpCode.HEARTBEAT_ACK || wsRes.t === SessionEvents.RESUMED) {
          if (!_this.alive) {
            _this.alive = true;
            _this.event.emit(SessionEvents.EVENT_WS, {
              eventType: SessionEvents.READY
            });
          }
          BotLogger.info('[CLIENT] 心跳校验', _this.heartbeatParam);
          setTimeout(function () {
            _this.sendWs(_this.heartbeatParam);
          }, _this.heartbeatInterval);
        }

        // 收到服务端锻炼重连的通知
        if (wsRes.op === OpCode.RECONNECT) {
          // 通知会话，当前已断线
          _this.event.emit(SessionEvents.EVENT_WS, {
            eventType: SessionEvents.RECONNECT
          });
        }

        // 服务端主动推送的消息
        if (wsRes.op === OpCode.DISPATCH) {
          // 更新心跳唯一值
          var _s = wsRes.s;
          if (_s) {
            _this.sessionRecord.seq = _s;
            _this.heartbeatParam.d = _s;
          }
          // OpenAPI事件分发
          _this.dispatchEvent(wsRes.t, wsRes);
        }
      });

      // 监听websocket关闭事件
      this.ws.on('close', function (data) {
        BotLogger.info('[CLIENT] 连接关闭', data);
        // 通知会话，当前已断线
        _this.alive = false;
        _this.event.emit(SessionEvents.EVENT_WS, {
          eventType: SessionEvents.DISCONNECT,
          eventMsg: _this.sessionRecord,
          code: data
        });
        if (data) {
          _this.handleWsCloseEvent(data);
        }
      });

      // 监听websocket错误
      this.ws.on('error', function () {
        BotLogger.info("[CLIENT] \u8FDE\u63A5\u9519\u8BEF");
        _this.event.emit(SessionEvents.CLOSED, {
          eventType: SessionEvents.CLOSED
        });
      });
      return this.ws;
    }

    // 连接ws
  }, {
    key: "connectWs",
    value: function connectWs(wsData) {
      // 创建websocket连接
      this.ws = new WebSocket(wsData.url);
    }

    // 鉴权
  }, {
    key: "authWs",
    value: function authWs() {
      // 鉴权参数
      var authOp = {
        op: OpCode.IDENTIFY,
        // 鉴权参数
        d: {
          token: "Bot ".concat(this.config.appID, ".").concat(this.config.token),
          // 根据配置转换token
          intents: this.getValidIntents(),
          // todo 接受的类型
          shard: this.checkShards(this.config.shards) || [0, 1],
          // 分片信息,给一个默认值
          properties: {
            $os: Properties.os,
            $browser: Properties.browser,
            $device: Properties.device
          }
        }
      };
      // 发送鉴权请求
      this.sendWs(authOp);
    }

    // 校验intents类型
  }, {
    key: "getValidIntents",
    value: function getValidIntents() {
      // 判断用户有没有给到需要监听的事件类型
      var intentsIn = this.getValidIntentsType();
      if (intentsIn.length > 0) {
        var intents = {
          value: 0
        };
        if (intentsIn.length === 1) {
          intents.value = IntentEvents[intentsIn[0]];
          return intents.value;
        }
        intentsIn.forEach(function (e) {
          intents.value = IntentEvents[e] | intents.value;
        });
        return intents.value;
      }
    }

    // 校验intents格式
  }, {
    key: "getValidIntentsType",
    value: function getValidIntentsType() {
      var intentsIn = this.config.intents;
      // 全部可监听事件
      var defaultIntents = Object.keys(AvailableIntentsEventsEnum);
      // 如果开发者没传intents，我们默认给他开启全部监听事件
      if (!intentsIn) {
        BotLogger.info('[CLIENT] intents不存在，默认开启全部监听事件');
        return defaultIntents;
      }
      // 如果开发者传入intents为空数组，我们默认给他开启全部监听事件
      if (intentsIn.length === 0) {
        BotLogger.info('[CLIENT] intents为空，默认开启全部监听事件');
        return defaultIntents;
      }
      // 如果intents大于可监听数
      if (intentsIn.length > defaultIntents.length) {
        BotLogger.info('[CLIENT] intents中的监听事件大于可监听数，仅开启有效监听事件');
      }
      // 如果intents中数据格式不对
      var typeIn = intentsIn.every(function (item) {
        return typeof item === 'string';
      });
      if (!typeIn) {
        BotLogger.info('[CLIENT] intents中存在不合法类型，仅开启有效监听事件');
        return intentsIn.filter(function (item) {
          return typeof item === 'string';
        });
      }
      return intentsIn;
    }

    // 校验shards
  }, {
    key: "checkShards",
    value: function checkShards(shardsArr) {
      // 没有传shards进来
      if (!shardsArr) {
        return BotLogger.info('shards 不存在');
      }
      // 传进来的符合要求
      if (Array.isArray(shardsArr) && shardsArr.length === 2 && shardsArr[0] < shardsArr[1]) {
        return shardsArr;
      }
      return BotLogger.info('shards 错误');
    }

    // 发送websocket
  }, {
    key: "sendWs",
    value: function sendWs(msg) {
      try {
        // 先将消息转为字符串
        this.ws.send(typeof msg === 'string' ? msg : JSON.stringify(msg));
      } catch (e) {
        BotLogger.info(e);
      }
    }

    // 重新连接
  }, {
    key: "reconnect",
    value: function reconnect() {
      BotLogger.info('[CLIENT] 等待断线重连');
    }

    // 重新重连Ws
  }, {
    key: "reconnectWs",
    value: function reconnectWs() {
      var reconnectParam = {
        op: OpCode.RESUME,
        d: {
          token: "Bot ".concat(this.config.appID, ".").concat(this.config.token),
          session_id: this.sessionRecord.sessionID,
          seq: this.sessionRecord.seq
        }
      };
      this.sendWs(reconnectParam);
    }

    // OpenAPI事件分发
  }, {
    key: "dispatchEvent",
    value: function dispatchEvent(eventType, wsRes) {
      var msg = wsRes.d;
      var eventId = wsRes.id || '';
      // 如果没有事件，即刻退出
      if (!msg || !eventType) return;
      this.event.emit(WsEventType[eventType], {
        eventType: eventType,
        eventId: eventId,
        msg: msg
      });
    }

    // 主动关闭会话
  }, {
    key: "closeWs",
    value: function closeWs() {
      this.ws.close();
    }

    // ws关闭的原因
  }, {
    key: "handleWsCloseEvent",
    value: function handleWsCloseEvent(code) {
      var _this2 = this;
      WebsocketCloseReason.forEach(function (e) {
        if (e.code === code) {
          _this2.event.emit(SessionEvents.ERROR, {
            eventType: SessionEvents.ERROR,
            msg: e.reason
          });
        }
      });
    }
  }]);
}();

var Session = /*#__PURE__*/function () {
  function Session(config, event, sessionRecord) {
    _classCallCheck$1(this, Session);
    _defineProperty$1(this, "config", void 0);
    _defineProperty$1(this, "heartbeatInterval", void 0);
    _defineProperty$1(this, "ws", void 0);
    _defineProperty$1(this, "event", void 0);
    _defineProperty$1(this, "sessionRecord", void 0);
    this.config = config;
    this.event = event;
    // 如果会话记录存在的话，继续透传
    if (sessionRecord) {
      this.sessionRecord = sessionRecord;
    }
    this.createSession();
  }

  // 新建会话
  return _createClass$1(Session, [{
    key: "createSession",
    value: function createSession() {
      var _this = this;
      this.ws = new Ws(this.config, this.event, this.sessionRecord || undefined);
      if (this.config.sandbox) {
        console.log('目前是沙箱模式');
      } else {
        console.log('目前是正式环境');
      }
      // 拿到 ws地址等信息
      var reqOptions = WsObjRequestOptions(this.config.sandbox);
      addAuthorization(reqOptions.headers, this.config.appID, this.config.token);
      Client.create(reqOptions).get(reqOptions.url, {}).then(function (r) {
        var wsData = r.data;
        if (!wsData) throw new Error('获取ws连接信息异常');
        _this.ws.createWebsocket(wsData);
      })["catch"](function (e) {
        BotLogger.info('[ERROR] createSession: ', e);
        _this.event.emit(SessionEvents.EVENT_WS, {
          eventType: SessionEvents.DISCONNECT,
          eventMsg: _this.sessionRecord
        });
      });
    }

    // 关闭会话
  }, {
    key: "closeSession",
    value: function closeSession() {
      this.ws.closeWs();
    }
  }]);
}();

function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
var MAX_RETRY = 10;
var WebsocketClient = /*#__PURE__*/function (_EventEmitter) {
  function WebsocketClient(config) {
    var _this;
    _classCallCheck$1(this, WebsocketClient);
    _this = _callSuper(this, WebsocketClient);
    _defineProperty$1(_this, "session", void 0);
    _defineProperty$1(_this, "retry", 0);
    _this.connect(config);
    _this.on(SessionEvents.EVENT_WS, function (data) {
      switch (data.eventType) {
        case SessionEvents.RECONNECT:
          BotLogger.info('[CLIENT] 等待断线重连中...');
          break;
        case SessionEvents.DISCONNECT:
          if (_this.retry < (config.maxRetry || MAX_RETRY)) {
            var _WebsocketCloseReason;
            BotLogger.info('[CLIENT] 重新连接中，尝试次数：', _this.retry + 1);
            _this.connect(config, (_WebsocketCloseReason = WebsocketCloseReason.find(function (v) {
              return v.code === data.code;
            })) !== null && _WebsocketCloseReason !== void 0 && _WebsocketCloseReason.resume ? data.eventMsg : null);
            _this.retry += 1;
          } else {
            BotLogger.info('[CLIENT] 超过重试次数，连接终止');
            _this.emit(SessionEvents.DEAD, {
              eventType: SessionEvents.ERROR,
              msg: '连接已死亡，请检查网络或重启'
            });
          }
          break;
        case SessionEvents.READY:
          BotLogger.info('[CLIENT] 连接成功');
          _this.retry = 0;
          break;
      }
    });
    return _this;
  }

  // 连接
  _inherits(WebsocketClient, _EventEmitter);
  return _createClass$1(WebsocketClient, [{
    key: "connect",
    value: function connect(config, sessionRecord) {
      var event = this;
      // 新建一个会话
      this.session = new Session(config, event, sessionRecord);
      return this.session;
    }

    // 断开连接
  }, {
    key: "disconnect",
    value: function disconnect() {
      // 关闭会话
      this.session.closeSession();
    }
  }]);
}(WebSocket.EventEmitter);

// 注册v1接口
v1Setup();
var defaultImpl = versionMapping[apiVersion];
// 如果需要使用其他版本的实现，需要在调用这个方法之前调用 SelectOpenAPIVersion 方法
function createOpenAPI(config) {
  return defaultImpl.newClient(config);
}
// ws连接新建
function createWebsocket(config) {
  return new WebsocketClient(config);
}

var sandbox = true; //是否是沙盒环境

// 公域QQ机器人
({
  appID: '102119535',
  token: '4qaPMu7OUWbc1dhoxZm4LZJNECalyE6j',
  appSecret: 'c9hFnLtRzY7gFoNwW6gGqQ0bCnOzaBnP',
  timeout: 3000,
  intents: [AvailableIntentsEventsEnum.GUILDS, AvailableIntentsEventsEnum.GUILD_MEMBERS, AvailableIntentsEventsEnum.DIRECT_MESSAGE, AvailableIntentsEventsEnum.AUDIO_ACTION],
  // 'AT_MESSAGES'
  shards: [0, 10],
  sandbox: sandbox
});

// 私域QQ机器人
var private_bot_config = {
  appID: '102119763',
  token: 'xxE7eajViIAxvb6oaKTFoCK3T3LxfWFo',
  appSecret: 'nu19HPXfnv4DMVenw5FPZjt3DOZkv6HS',
  timeout: 3000,
  intents: [AvailableIntentsEventsEnum.GUILDS, AvailableIntentsEventsEnum.GUILD_MEMBERS, AvailableIntentsEventsEnum.DIRECT_MESSAGE, AvailableIntentsEventsEnum.AUDIO_ACTION, AvailableIntentsEventsEnum.FORUMS_EVENT],
  // 'AT_MESSAGES'
  shards: [0, 10],
  sandbox: sandbox
};

function get(url, params) {
  return new Promise(function (resolve, reject) {
    axios.get(url, {
      params: params
    }).then(function (response) {
      resolve(response.data);
    })["catch"](function (error) {
      reject(error);
      console.log(error);
    });
  });
}
var getNews = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          return _context.abrupt("return", get('http://excerpt.rubaoo.com/toolman/getMiniNews'));
        case 1:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return function getNews() {
    return _ref.apply(this, arguments);
  };
}();

var client = createOpenAPI(private_bot_config);
var ws = createWebsocket(private_bot_config);
var guilds = [];
var channels = [];
ws.on('READY', /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(wsdata) {
    var response, _yield$client$meApi$m, data, _yield$client$channel, datachannels, channelID, content, _yield$client$channel2;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          console.log('[READY] 事件接收 :', wsdata);
          _context.next = 3;
          return getNews();
        case 3:
          response = _context.sent;
          _context.next = 6;
          return client.meApi.meGuilds();
        case 6:
          _yield$client$meApi$m = _context.sent;
          data = _yield$client$meApi$m.data;
          guilds = data;
          // 获取子频道列表
          if (!(guilds.length > 0)) {
            _context.next = 22;
            break;
          }
          _context.next = 12;
          return client.channelApi.channels(guilds[0].id);
        case 12:
          _yield$client$channel = _context.sent;
          datachannels = _yield$client$channel.data;
          channels = datachannels;
          console.log(channels);
          //在子频道-论坛子频道-发布帖子
          channelID = channels.filter(function (item) {
            return item.type == 10007;
          })[0].id;
          content = response.data.news.map(function (item) {
            return item + '\n';
          }).join('');
          _context.next = 20;
          return client.channelApi.createThreads(channelID, {
            title: response.data.date,
            // content: "<html lang=\"en-US\"><body><img src=\"https://fc1tn.baidu.com/it/u=1805636791,639113867&fm=202&mola=new&crop=v1\"  /></body></html>",
            content: content,
            format: 1
          });
        case 20:
          _yield$client$channel2 = _context.sent;
          _yield$client$channel2.data;
        case 22:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return function (_x) {
    return _ref.apply(this, arguments);
  };
}());
ws.on('ERROR', function (data) {
  console.log('[ERROR] 事件接收 :', data);
});
ws.on('GUILDS', function (data) {
  console.log('[GUILDS] 事件接收 :', data);
});
ws.on('GUILD_MEMBERS', function (data) {
  console.log('[GUILD_MEMBERS] 事件接收 :', data);
});
ws.on('GUILD_MESSAGES', function (data) {
  console.log('[GUILD_MESSAGES] 事件接收 :', data);
});
ws.on('GUILD_MESSAGE_REACTIONS', function (data) {
  console.log('[GUILD_MESSAGE_REACTIONS] 事件接收 :', data);
});
ws.on('DIRECT_MESSAGE', function (data) {
  console.log('[DIRECT_MESSAGE] 事件接收 :', data);
});
ws.on('INTERACTION', function (data) {
  console.log('[INTERACTION] 事件接收 :', data);
});
ws.on('MESSAGE_AUDIT', function (data) {
  console.log('[MESSAGE_AUDIT] 事件接收 :', data);
});
ws.on('FORUMS_EVENT', function (data) {
  console.log('[FORUMS_EVENT] 事件接收 :', data);
});
ws.on('AUDIO_ACTION', function (data) {
  console.log('[AUDIO_ACTION] 事件接收 :', data);
});
ws.on('PUBLIC_GUILD_MESSAGES', /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(eventData) {
    var _yield$client$message, data;
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          console.log('[PUBLIC_GUILD_MESSAGES] 事件接收 :', eventData);
          _context2.next = 3;
          return client.messageApi.postMessage('', {
            content: 'test'
          });
        case 3:
          _yield$client$message = _context2.sent;
          data = _yield$client$message.data;
          console.log(data);
        case 6:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
  return function (_x2) {
    return _ref2.apply(this, arguments);
  };
}());
ws.on('INTERACTION', function (data) {
  console.log('[INTERACTION] 事件接收 :', data);
});

// 获取当前加入了哪些频道

// client.guildApi.guild('').then((data) => {
//   console.log(data);
// });

// // ✅
// client.channelApi.channels(guildID).then((res) => {
//   console.log(res.data);
// });
